简体   繁体   English

具有C结构的C#Pinvoke包含函数指针

[英]C# Pinvoke with C struct contains function pointer

I struggled this for a while, still not able to figured out how to write code in C# side 我为此挣扎了一段时间,仍然无法弄清楚如何在C#端编写代码

C++ DLL C ++ DLL

typedef void (WINAPI *P_HelloWorld)(void);
typedef struct {

P_HelloWorld pHelloWorld;

}FUNC_PARAM;

void Func4(FUNC_PARAM* pFunc)
{
   pFunc.pHelloWorld();
}

C# Side: C#面:

public delegate void P_HelloWord();
[StructLayout(LayoutKind.Sequential)]
public struct FUNC_PARAM
 {
   public P_HelloWord pHelloWorld;
 }

  [DllImport("EMV_DLL.dll")]

  public extern static void Func4(FUNC_PARAM[] pFunc);

 void main()
 {
   FUNC_PARAM g;
   g.pHelloWorld = new P_HelloWord(this.myHelloWorld);
   Func4(new FUNC_PARAM[] { g });
  }

void myHelloWorld()
{
   MessageBox.Show("My Hello World");
}

The above C# code doesn't work, when execute Func4 function, it throws out of memory exception. 上面的C#代码不起作用,当执行Func4函数时,它将抛出内存不足异常。

Anybody could help me? 有人可以帮助我吗?

You don't appear to have posted the real code since the code in your question does not compile. 由于问题中的代码无法编译,因此您似乎没有发布真实的代码。 Anyway, the following does work. 无论如何,以下方法确实有效。

C++ C ++

typedef void (WINAPI *P_HelloWorld)(void);

typedef struct {
    P_HelloWorld pHelloWorld;
} FUNC_PARAM;

void Func4(FUNC_PARAM* pFunc)
{
   pFunc->pHelloWorld();
}

C# C#

public delegate void P_HelloWord();

public struct FUNC_PARAM
{
    public P_HelloWord pHelloWorld;
}

[DllImport(@"MyDll.dll", CallingConvention = CallingConvention.Cdecl)]
public extern static void Func4(ref FUNC_PARAM pFunc);

static void Main(string[] args)
{
    FUNC_PARAM pFunc;
    pFunc.pHelloWorld = myHelloWorld;
    Func4(ref pFunc);
    Console.ReadLine();
}

static void myHelloWorld()
{
    Console.WriteLine("Boo!");
}

Some points: 一些要点:

  1. The parameter to Func4 is not an array. Func4的参数不是数组。 It's the address of the struct. 这是结构的地址。 So that makes it ref in C#. 这样就可以在C#中进行ref
  2. The calling convention for Func4 is cdecl . Func4的调用约定为cdecl
  3. The implementation of Func4 does not compile in your code. Func4的实现未在您的代码中编译。 I fixed it in mine. 我把它固定在我的。
  4. Your C# main function was incorrect. 您的C#主要功能不正确。 It has to be a function declared as per my code. 它必须是根据我的代码声明的函数。

Apparently you are using CE. 显然您正在使用CE。 There only is one calling convention there, stdcall. 那里只有一种调用约定,stdcall。 As for the error you report in the comments, stop wrapping the delegate in a struct and pass it directly. 至于您在注释中报告的错误,请停止将委托包装在结构中并直接传递。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM