Equivalent to char * in C #
I have a dll written in C ++. And I p / call to call the functions.
I have this C ++ declaration.
int dll_registerAccount(char* username, char* password);
I made this dllimport declaration:
[DllImport("pjsipDlld")]
static extern int dll_registerAccount(IntPtr username, IntPtr password);
Will my DllImport be the C ++ equivalent using IntPtr?
Thanks a lot for any advice,
source to share
The C # way to do this is to let the marshaller process the elements char*
while working with the string:
[DllImport("pjsipDlld")]
static extern int dll_registerAccount(
[MarshalAs(UnmanagedType.LPStr)]string username,
[MarshalAs(UnmanagedType.LPStr)]string password);
Replace LPStr
with LPWStr
if you are working with wide characters.
source to share
I launched your C ++ line via P / Invoke :
public partial class NativeMethods {
/// Return Type: int
///username: char*
///password: char*
[System.Runtime.InteropServices.DllImportAttribute("<Unknown>", EntryPoint="dll_registerAccount")]
public static extern int dll_registerAccount(System.IntPtr username, System.IntPtr password) ;
}
So you were right, it should work. But there are several automatic marshaling, you may only be able to do:
[DllImport("pjsipDlld")]
static extern int dll_registerAccount(string username, string password);
See MSDN page about default marshaling and override it.
source to share
Be aware of calling conventions, it worked. In my case, I need to call a C ++ DLL, but with a C style export that uses the calling convention cdecl
. If you have the luxury of having a native 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);
source to share
[DllImport("DLL loction"),EntryPoint = "dll_registerAccount", CallingConvention = CallingConvention.Cdecl)]
[return : MarshalAs(UnmanagedType.I4)]
static extern int dll_registerAccount(
[MarshalAs(UnmanagedType.LPStr)]string username,
[MarshalAs(UnmanagedType.LPStr)]string password);
- 'cdecl' is the default calling convention for C and C ++ programs
- Refer to these doc1 for more information
source to share