Birnbacherin Birnbacherin - 1 month ago 10
C# Question

C# import dll function with const string& as parameter

I have written a Banking System DLL in C++ with a C Interface with the following function that is used to rename a customer:

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


Now I want to use the function in a .NET Assembly. I tried to import the function from the dll this way

[DllImport("BankManagement.dll", EntryPoint = "renameCustomer", CallingConvention = CallingConvention.Cdecl)]
public static extern int renameCustomer(ref string firstname_, ref string name_, uint customerId_);


and I would like to use it in the following function:

public int changeCustomerName(uint id_, string firstname_, string name_)
{
return renameCustomer(ref firstname_, ref name_, id_);
}


In a test application I call the function this way:

BankManageIntern.BankIntern myBankIntern = new BankManageIntern.BankIntern();
int checkCust = myBankIntern.changeCustomerName(0, "Name", "Firstname");


My Logger shows me that the customer could not be renamed because the input for name is empty. Now I believe that I made a mistake passing the strings to the functions. I have already tried all kinds of ways to pass the string, which I found on Google, but nothing works. Does anybody of you have an idea? The customer exists and the customer id is valid. I'm sure that's not the problem.

One condition is that I may not change the Function of the DLL. I can only make changes in the .NET Assembly and the Application.

Answer

try the following:

instead of trying to pass an string, use an pointer to an char. this can be done by using an IntPtr.

private static extern int renameCustomer( IntPtr firstname, IntPtr lastname, uint id);

in your Application you can use the var datatype. It's similar to the auto_ptr in C++.

var firstnamePtr = Marshal.StringToHGlobalAnsi(firstname);
var lastnamePtr = Marshal.StringToHGlobalAnsi(lastname);

and call with that your function from the DLL.

var status = renameCustomer(firstnamePtr, lastnamePtr, id);

Hope that will help you with your problem! :)