Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

equivalent char* in C#

I have a dll that is written in c++. And I am p/invoking to call the functions.

I have this c++ declaration.

int dll_registerAccount(char* username, char* password);

I have done this dllimport declaration:

[DllImport("pjsipDlld")]
static extern int dll_registerAccount(IntPtr username, IntPtr password);

Would my DllImport be the equivalent to the c++ using IntPtr?

Many thanks for any advice,

like image 601
ant2009 Avatar asked Nov 28 '22 05:11

ant2009


2 Answers

The C# way of doing this is by letting the marshaler handle the char* stuff while you work with a string:

[DllImport("pjsipDlld")]
static extern int dll_registerAccount(
    [MarshalAs(UnmanagedType.LPStr)]string username,
    [MarshalAs(UnmanagedType.LPStr)]string password);

Replace LPStr with LPWStr if you're working with wide chars.

like image 165
Blindy Avatar answered Dec 18 '22 10:12

Blindy


Be aware of calling conventions, this tripped me up. In my case I need to call a C++ DLL but with C-style exports, which uses the cdecl calling convention. If you have the luxury of having the source Visual Studio Solution, go to Properties -> C/C++ -> Advanced and find it under "Calling Convention". This fix it for me:

[DllImport(DllName, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
// bool MyFunction(char* fileName) <-- From the DLL
static extern bool MyFunction(string fileName);
like image 35
Steztric Avatar answered Dec 18 '22 11:12

Steztric