将C#数据类型参数传递给用C ++编写的dll? [英] Passing C# data type parameters to dll written in C++?

查看:234
本文介绍了将C#数据类型参数传递给用C ++编写的dll?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仍在处理从此处开始的问题
从C#调用C ++ dll函数:struct,string和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中的unmanages类。

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?

推荐答案

数据类型是使用 PInvoke Interop Assitant 。它将为大多数C结构创建适当的C#/ VB.Net类型。这里是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;
}

对于char *参数,可以传递IntPtr.Zero或使用Marshal。 StringToCoTaskMemAnsi来完成作业。

For the char* parameter, you can pass IntPtr.Zero or use Marshal.StringToCoTaskMemAnsi to get the job done.

这篇关于将C#数据类型参数传递给用C ++编写的dll?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆