[英]C# import dll function with const string& as parameter
我已经用C语言编写了带有C接口的C ++银行系统DLL,该函数具有用于重命名客户的以下功能:
int renameCustomer(const string& firstname_, const string& name_, const unsigned int customerId_);
现在,我想在.NET Assembly中使用该函数。 我试图以这种方式从dll导入功能
[DllImport("BankManagement.dll", EntryPoint = "renameCustomer", CallingConvention = CallingConvention.Cdecl)]
public static extern int renameCustomer(ref string firstname_, ref string name_, uint customerId_);
我想在以下功能中使用它:
public int changeCustomerName(uint id_, string firstname_, string name_)
{
return renameCustomer(ref firstname_, ref name_, id_);
}
在测试应用程序中,我以这种方式调用该函数:
BankManageIntern.BankIntern myBankIntern = new BankManageIntern.BankIntern();
int checkCust = myBankIntern.changeCustomerName(0, "Name", "Firstname");
我的记录器向我显示,由于名称输入为空,因此无法重命名客户。 现在,我相信将字符串传递给函数时犯了一个错误。 我已经尝试了各种方法来传递字符串,这是我在Google上发现的,但是没有任何效果。 你们有主意吗? 客户存在且客户ID有效。 我敢肯定那不是问题。
一种情况是我可能不会更改DLL的功能。 我只能在.NET程序集和应用程序中进行更改。
尝试以下方法:
与其尝试传递字符串,不如使用指向char的指针。 这可以通过使用IntPtr完成。
private static extern int renameCustomer( IntPtr firstname, IntPtr lastname, uint id);
在您的应用程序中,您可以使用var数据类型。 它类似于C ++中的auto_ptr。
var firstnamePtr = Marshal.StringToHGlobalAnsi(firstname);
var lastnamePtr = Marshal.StringToHGlobalAnsi(lastname);
然后从DLL中调用该函数。
var status = renameCustomer(firstnamePtr, lastnamePtr, id);
希望能对您的问题有所帮助! :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.