I wrote a C ++ / CLI wrapper for C ++ - DLLs to use this DLL in a C # program.
However, when I call a function that accepts char *, I get AccessViolation
int Wrapper::Net_methodX(int a, String^ key, long v)
{
IntPtr ptr = Marshal::StringToHGlobalAnsi(key);
pin_ptr<char> cKey = static_cast<char*>(ptr.ToPointer());
int val = methodX(a,cKey, v);
Marshal::FreeHGlobal(ptr);
return val;
}
C ++ Signature - Functions
int methodX(int a, char *Key, long v);
EDIT 1
Just to “output”, like the following, it didn’t work:
int Wrapper::Net_methodX(int a, String^ key, long v)
{
IntPtr ptr = Marshal::StringToHGlobalAnsi(key);
char* cKey = static_cast<char*>(ptr.ToPointer());
pin_ptr<char> pinned = cKey;
int val = methodX(a,cKey, v);
Marshal::FreeHGlobal(ptr);
return val;
}
EDIT 1 END
EDIT 2
I also tried PtrToStringChars as follows (thanks Matt, I also found some document here ):
int Wrapper::Net_methodX(int a, String^ key, long v)
{
pin_ptr<const wchar_t> wkey = PtrToStringChars(key);
size_t convertedChars = 0;
size_t sizeInBytes = ((key->Length + 1) * 2);
errno_t err = 0;
char * ckey = (char * ) malloc(sizeInBytes);
err = wcstombs_s(&convertedChars, ckey, sizeInBytes, wkey, sizeInBytes);
int val = methodX(A_Symbol_Table,ckey, Value);
return val;
}
AccessViolation still exists, maybe this is an error in the X () method (which is a third-party DLL).
EDIT 2 END
I read some related questions here, but have not yet found a solution.
Any clues? Thank.