本文介绍了从非托管C ++调用C#代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Mono中,你可以将一个委托从C#传递给一个C ++函数,它将委托作为一个函数指针。这可以在Windows上的C#中完成,例如,您可以编译一个本地C ++非托管库,将其链接到一个C#项目,并获得一个C ++函数通过一个函数指针调用C#函数,C#作为委托传递给它? / p>

In Mono you can pass a delegate from C# to a C++ function which takes in the delegate as a function pointer. Can this be done in C# on Windows for example where you can compile a native C++ unmanaged library, link it against a C# project and get a C++ function to invoke a C# function via a function pointer which C# passed to it as a delegate?

推荐答案

在.NET中定义一个委托,然后将它传递给你的非托管代码。 CLR会将委托公开为一个函数指针,可以从非托管代码中调用。

Define a delegate in .NET, and then pass that to your unmanaged code. The CLR will expose the delegate as a function pointer which you can call from your unmanaged code.

互操作层不知道如何处理C ++中的引用。所以你需要将对象暴露为指针,而不是引用。此外,.NET不知道什么是C ++
对象(它不同于System.Object)。这将需要传递
作为IntPtr,我不认为有很多你可以做它在.NET。

The interop layer does not know how to handle references in C++. So You need to expose the object as a pointer, not a reference. Additionally, .NET doesn't know what a C++object is (it's not the same as System.Object). That will need to be passedas an IntPtr, and I don't think there is much you can do with it in .NET.

C ++回调:

typedef void (*CBFUNC1)(unsigned int, const char*, object&);
typedef object* (*CBFUNC2)(object*, struct _mystruct* );

代表的C#签名将是

delegate void CbFunc1(uint param1, [MarshalAs(UnmanagedType.LPStr)] string
param2, IntPtr param3);
delegate IntPtr CbFunc2(IntPtr param1, ref _mystruct param2);

这篇关于从非托管C ++调用C#代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 12:40