调用包含从C#中的函数指针DLL函数 [英] Calling a DLL function that contains a function pointer from C#

查看:1191
本文介绍了调用包含从C#中的函数指针DLL函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用C ++编写,包括导出函数具有函数指针用作回调函数的DLL。

I have a DLL that is written in C++ that includes exported function that has a function pointers to be used as callback function.

// C++ 
DllExport unsigned int DllFunctionPointer( unsigned int i, unsigned int (*TimesThree)( unsigned int number ) ) {
    return TimesThree( i )  ; 
}



我有,我想用来调用DLL函数CSHARP应用。

I have a CSharp application that I would like to use to invoke the DLL functions.

// 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 ; 
    }
}



与上面的代码的问题是,应用程序崩溃用下面的错误消息。

The problem with the above code is that the application crashes with the following error message.

'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).



我不知道下一步该怎么做。

I am not sure what to do next.

我的问题是:


  • 什么是调用C正确的方法+包含从C#应用程序回调指针DLL函数。

推荐答案

这是因为默认情况下调用的函数约定在 C# __ STDCALL C / C ++ 默认为 __ CDECL ,所以你应该改变你的调用函数的约定如下:

This is because by default calling convention of functions in C# is __stdcall but in C/C++ default is __cdecl, so you should change calling convention of your function as follow:

[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 );
    // ...
}

这篇关于调用包含从C#中的函数指针DLL函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆