C# import dll 函数与 const string&as 参数



我用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");

My Logger显示无法重命名客户,因为name的输入为空。现在我相信我犯了一个错误,把字符串传递给函数。我已经尝试了各种方法来传递字符串,这是我在谷歌上发现的,但没有任何效果。你们有人知道吗?客户存在且客户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);

希望这将帮助您解决您的问题!:)

相关内容

最新更新