I have the following test function set up in a C project:
__declspec(dllexport) int test(char *str, int strlen){
char* h = "Hello";
int length = 5;
for(int i = 0; i < length; i++){
str[0] = h[0];
}
return strlen;
}
And in my C# project I declare the method as follows:
[DllImport("solver.dll", CharSet = CharSet.Unicode ,CallingConvention = CallingConvention.Cdecl)]
public static extern int test(StringBuilder sol, int len);
And I try to use it in my project like so:
StringBuilder sol = new StringBuilder(15);
int t = test(sol, sol.Capacity);
string str = sol.ToString();
I'd like to pass "Hello" back to the C# code as a test, but when I run the code the StringBuilder stays empty, and even though 15 is passed to the C function as the length, when the C function returns the length it returns a 'random' large number like 125822695. What am I missing?
charis MBCS, not Unicode. Try to change that towchar_t. But I think there is more missing. Have you tried doing it the other way around, i.e. creating a C++/CLR wrapper (managed C++) around your C library and use that instead of directly messing withDllImport?CharSet = CharSet.Unicode, but it looks like it's using 8 bit chars to me. Secondly,str[0] = h[0];... Should that not bestr[i] = h[i];? Actually, it looks like there may be other bugs in the C function. I would suggest you (unit) test it properly within the C environment, before trying to call it from C#.Unicodewhen you know that it isAnsi. Don't attempt to write code by trial and error.