【问题标题】:C# import dll function with const string& as parameterC# 以 const string& 为参数导入 dll 函数
【发布时间】:2016-10-24 09:51:51
【问题描述】:

我用 C++ 编写了一个银行系统 DLL,它带有一个 C 接口,它具有以下用于重命名客户的函数:

int renameCustomer(const string& firstname_, const string& name_, const unsigned int customerId_);

现在我想在 .NET 程序集中使用该函数。我试图以这种方式从 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");

我的记录器显示无法重命名客户,因为名称输入为空。现在我相信我将字符串传递给函数时犯了一个错误。我已经尝试了各种方法来传递我在谷歌上找到的字符串,但没有任何效果。你们有人有想法吗?客户存在且客户 ID 有效。我确定这不是问题。

一个条件是我不能更改 DLL 的功能。我只能在 .NET 程序集和应用程序中进行更改。

【问题讨论】:

标签: c# string dll reference parameter-passing


【解决方案1】:

尝试以下方法:

不要尝试传递字符串,而是使用指向 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);

希望对您的问题有所帮助! :)

【讨论】:

  • 谢谢!这有很大帮助:-D!
猜你喜欢
  • 2013-12-21
  • 1970-01-01
  • 1970-01-01
  • 2016-05-23
  • 1970-01-01
  • 1970-01-01
  • 2013-03-14
  • 2021-12-31
  • 1970-01-01
相关资源
最近更新 更多