简体   繁体   English

如何将C#函数指针传递给CLI / C ++代码?

[英]How can I pass a C# function pointer into CLI/C++ code?

I want unmanaged C++ code to call a C# function as a callback. 我希望非托管C ++代码将C#函数作为回调来调用。 I have a CLI/C++ class wrapping around the unmanaged code. 我有一个环绕非托管代码的CLI / C ++类。 An instance of this CLI/C++ class exists within the C#. 此CLI / C ++类的实例存在于C#中。

The C# code looks like the below text. C#代码看起来像下面的文本。 I have a (delegate) function pointer to the callBack method. 我有一个(委托)函数指针,指向callBack方法。 I have the CLI instance of CLI_class. 我有CLI_class的CLI实例。 I want to give it the function pointer somehow in the addValueChangedCallBack function. 我想在addValueChangedCallBack函数中以某种方式为它提供函数指针。

public Setup(){
    tempFUNC myFuncObj = new tempFUNC(callBack)
    CLI_class c=new CLI_class();
    c.addValueChangedCallBack(myFuncObj)
}

public delegate void tempFUNC(float x);

void callBack(float x){
....
}

Then in the CLI code I want to do something like this: 然后在CLI代码中,我想执行以下操作:

void addValueChangedCallback(void (*ManipCallBack)(float)){
   unmanagedCPPCLASS.addValueChangedCallback(ManipCallBack)

}

How can I turn the function pointer into a C++ pointer (*)? 如何将函数指针转换为C ++指针(*)? Also, I cannot reference the C# project in the C++/CLI project because the C# class already references and uses the C++/CLI project. 另外,我无法在C ++ / CLI项目中引用C#项目,因为C#类已经引用并使用了C ++ / CLI项目。 Will there be a dependency issue? 会有依赖问题吗?

I have seen references on some sites to 'marshaling data' or using 'interop'. 我在某些站点上看到过“封送数据”或“互操作”的引用。 I don't understand how they work or what exactly they do from anything I have seen, are these what I should be using? 我不了解它们的工作原理或从我所看到的一切中可以确切地做什么,这些我应该使用吗?

You can have both projects reference each other and use System.InteropServices.Runtime.Marshal.GetFunctionPointerForDelegate to get the function pointer. 您可以使两个项目相互引用,并使用System.InteropServices.Runtime.Marshal.GetFunctionPointerForDelegate来获取函数指针。

But if I were you I'd make the C# class ComVisible and have the C++ code call the C# method directly though a COM interface. 但是,如果您是我,那么我将使C#类成为ComVisible并让C ++代码通过COM接口直接调用C#方法。 That way there's no need for a C++/CLI wrapper. 这样就不需要C ++ / CLI包装器。 Wrappers are always a pain, as you're experiencing. 如您所见,包装总是很痛苦的。 C++/CLI has its uses, but creating wrappers is not it. C ++ / CLI有其用途,但不是创建包装器。

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

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