且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将非托管C ++方法传递给C#dll以进行回调

更新时间:2023-02-12 18:21:54

好吧,比我想象的容易,但看起来像巫毒我...



基本上在c ++中添加

  void CALLBACK CppCallbackc()
{
std :: cout<< 测试;
}

然后在c#add

  public delegate void CppCallback(); 

,当您要启动它时,

  Marshal.GetDelegateForFunctionPointer(cppCallback,typeof(CppCallback))。DynamicInvoke(null); 


I have a .Net dll which I have registered and am able to call methods on from my C# code. I essentially followed this tutorial: http://support.microsoft.com/kb/828736

now I need to do something in c# asynchronously, so I need some way of telling the c++ code that I am done.

I have created a method like so:

public void Init(string server, IntPtr callback); 

which I can see in the c++ as:

Init(BSTR server, long callback);

I also need to pass a variable back to the c++ code when I make invoke it.

basically, I have an event that's getting fired in the C# code and I need the c++ code to handle it, including the event args.

I am glad to do the reading myself, but I am not able to find anything at all. I did see some stuff about windows events... here http://msdn.microsoft.com/en-us/library/windows/desktop/aa385771(v=vs.85).aspx

but we aren't using any windows headers I don't think and I didn't want to add all this stuff if there is a simpler way of doing this.

Thank you for reading!

okay it's easier than I thought, but it seems like voodoo to me...

basically in the c++ add

void CALLBACK CppCallbackc()
{
    std::cout << "test";
}

then in the c# add

public delegate void CppCallback();

and when you want to fire it,

Marshal.GetDelegateForFunctionPointer(cppCallback, typeof(CppCallback)).DynamicInvoke(null);