传递C#数据类型参数,DLL用C ++编写?
上还是从这里开始的一个问题工作
的调用C ++ DLL函数从C#:。结构,字符串和wchar_t的阵列,但用不同的方法
Still working on a problem that started from here Calling C++ dll function from C#: Of structs, strings and wchar_t arrays., but with a different approach.
继这个例子中调用从非托管代码托管代码,反之亦然我写了一个托管包装在C ++访问取消管理类的非托管C ++的dll
Following the example Calling Managed Code from Unmanaged Code and vice-versa I wrote a managed wrapper in C++ to access the unmanages class in the unmanaged C++ dll.
它看起来是这样的:
//in header file
public __gc class TSSLDllWrapper
{
public:
TSSLDllWrapper();
//this is the unmanaged class
CcnOCRsdk * _sdk;
bool convertHKID_Name(char *code, RECO_DATA *o_data);
};
//in .cpp file
TSSLDllWrapper::TSSLDllWrapper(void)
{
_sdk = new CcnOCRsdk();
}
bool TSSLDllWrapper::convertHKID_Name(char *code, RECO_DATA *o_data)
{
return _sdk->convertHKID_Name(code, o_data);
}
//C++ RECO_DATA structure definition:
struct RECO_DATA{
wchar_t FirstName[200];
wchar_t Surname[200];
};
现在我有一个dll,我可以导入到我的C#项目。
Now I have a dll that I can import into my C# project.
下面然而问题:
当我想从dll文件调用方法,就像这样:
Here is the problem however: When I want to call the method from the dll file, like this:
TSSLDllWrapper wrapper = new TSSLDllWrapper();
bool res = wrapper.convertHKID_NameSimple( //need to pass parameters here );
据预计,C ++参数 - 指向char和RECO_DATA
It expects the C++ parameters - pointers to char and RECO_DATA.
我怎样才能解决这个问题,并从C#代码通过C ++类型?
How can I fix this and pass C++ types from C# code?
对于大多数C转换的一种方法数据类型是使用的PInvoke互操作Assitant 。它将创建适当的C#/ VB.Net类型最C结构。这里是输出RECO_DATA
One way to convert most C data types is to use the PInvoke Interop Assitant. It will create proper C# / VB.Net types for most C structures. Here is the output for RECO_DATA
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, CharSet=System.Runtime.InteropServices.CharSet.Unicode)]
public struct RECO_DATA {
/// wchar_t[200]
[System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst=200)]
public string FirstName;
/// wchar_t[200]
[System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst=200)]
public string Surname;
}
有关的字符*参数,你可以传递IntPtr.Zero或使用元帅。 StringToCoTaskMemAnsi来完成这项工作。
For the char* parameter, you can pass IntPtr.Zero or use Marshal.StringToCoTaskMemAnsi to get the job done.