C# 调用包含来自C的函数指针的DLL函数# 我有一个用C++编写的DLL,包含导出函数,它有一个指针用作回调函数。p> // C++ DllExport unsigned int DllFunctionPointer( unsigned int i, unsigned int (*TimesThree)( unsigned int number ) ) { return TimesThree( i ) ; }

C# 调用包含来自C的函数指针的DLL函数# 我有一个用C++编写的DLL,包含导出函数,它有一个指针用作回调函数。p> // C++ DllExport unsigned int DllFunctionPointer( unsigned int i, unsigned int (*TimesThree)( unsigned int number ) ) { return TimesThree( i ) ; },c#,c++,dll,function-pointers,C#,C++,Dll,Function Pointers,我有一个CSharp应用程序,我想用它来调用DLL函数 // C# public unsafe delegate System.UInt32 CallBack( System.UInt32 number ); class Program { [DllImport("SimpleDLL.dll")] public static extern System.UInt32 DllFunctionPointer( System.UInt32 i, CallBack cb) ;

我有一个CSharp应用程序,我想用它来调用DLL函数

// C#
public unsafe delegate System.UInt32 CallBack( System.UInt32 number ); 
class Program
{
    [DllImport("SimpleDLL.dll")]
    public static extern System.UInt32 DllFunctionPointer( System.UInt32 i, CallBack cb) ;

    static unsafe void Main(string[] args)
    {
        System.UInt32 j = 3;
        System.UInt32 jRet = DllFunctionPointer(j, CallBack );
        System.Console.WriteLine("j={0}, jRet={1}", j, jRet); 
    }

    static System.UInt32 CallBack( System.UInt32 number ) {
        return number * 3 ; 
    }
}
上面代码的问题是应用程序崩溃并显示以下错误消息

'CallingACallbackFromADLL.vshost.exe' (Managed (v4.0.30319)): Loaded 'C:\XXXX\CallingACallbackFromADLL.exe', Symbols loaded.
Managed Debugging Assistant 'PInvokeStackImbalance' has detected a problem in 'C:\XXXX\CallingACallbackFromADLL.vshost.exe'.
Additional Information: A call to PInvoke function 'CallingACallbackFromADLL!CallingACallbackFromADLL.Program::DllFunction' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature.

The program '[9136] CallingACallbackFromADLL.vshost.exe: Managed (v4.0.30319)' has exited with code 1073741855 (0x4000001f).
我不知道下一步该怎么办

我的问题是:

    <>从C++应用程序调用包含回调指针的C++ DLL函数的正确方法是什么?<李>
这是因为默认情况下,
C
中函数的调用约定是
\uu stdcall
,但在
C/C++
中,默认值是
\uu cdecl
,因此您应该按如下方式更改函数的调用约定:

[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void TimesTree( uint frame );
[DllImport("SimpleDLL.dll")]
public static extern System.UInt32 DllFunctionPointer( uint i,
    [MarshalAs(UnmanagedType.FunctionPtr)] TimesTree callback ) ;

static unsafe void Main(string[] args)
{
    // ...
    System.UInt32 jRet = DllFunctionPointer(j, CallBack );
    // ...
}

[UnmanagedFunctionPointer(CallingConvention.Cdecl)]的可能doop只有在x86(Win32/WoW64)模式下运行时才需要此选项。在64位模式下,只有一个调用约定,并且忽略此属性。如果在X64机上开发,您可能会轻易忘记32位的特殊处理。@错误>代码>不平衡堆栈只会导致C++函数中的堆栈变量中的<代码>下溢/溢出>代码>(在<代码> C<<代码>中,您不能这样做)或不良调用约定。所以调用方肯定不是在X64模式下运行代码!