所以几个星期后,我能够得到一些东西,我想我会分享给小组。 (赦免伪码外观)。我基本上自学了C#而不是C++/CLI。
记住问题 - C++模板函数(如下面的VS所示)可以用C#编组吗?
我的解决方法如下:将封送的非托管C#调用转换为可以将调用转换为模板方法的C++函数。
这里是代码:
//C++ code
//C++ Header
class __declspec(dllexport) Foo
{
public:
template <typename T> T* getFoo(T* fooData){return fooData;};
};
extern "C" __declspec(dllexport) void call_getFoo(Foo* pFoo, void* pfooData, int fooId)
{
switch(fooId)
{
case(ENUM::1) : //Use an enum here for a better switch statement.
{
//Cast the void pointer to a specific type so the template knows how to use it.
pFoo->getFoo((*TypeCast*)pfooData);
break;
}
}
}
//C# Code
internal static class UnsafeNativeMethods
{
const string _dllLocation = "Foo.dll";
[DllImport(_dllLocation)]
static public extern void call_getFoo(IntPtr pFoo, IntPtr pfooData, int fooId);
}
//In a C# method
...
...
//Marshal Up a C# data type to a pointer for C++.
*YOUR TYPE HERE* myType;
int rawsize = Marshal.SizeOf(myType);
IntPtr pfooData = Marshal.AllocHGlobal(rawsize);
Marshal.StructureToPtr(myType,pfooData,true);
//call the C++ dll
UnsafeNativeMethods.call_getFoo(pFoo, pfooData, fooId);
//Convert Ptr Back To myType
myType = (*YOUR TYPE HERE*) Marshal.PtrToStructure(pfooData, typeof(*YOUR TYPE HERE*));
...
...
希望帮助!
来源
2011-06-02 22:20:58
LEO
@Yhai这不是同一个问题。 – 2011-05-19 14:09:04
@Yochai:这个问题不是关于移植,而是接口。 LEO仍计划使用C++来构建DLL。甚至不接近愚蠢。 – 2011-05-19 14:09:05