I am trying to create a win32 dll that provides some functions that are called in c # as follows
__declspec(dllexport) int GetData(unsigned char* *data, int* size) { try { int tlen = 3; unsigned char* tchr = new unsigned char[5]; tchr[0] = 'a'; tchr[1] = 'b'; tchr[2] = 'c'; *size = tlen; *data = tchr; return 1; } catch (char *p) { return 0; } }
And on the C # side
[DllImport("MyDll.dll")] static extern int GetData(ref byte[] data, ref int size); static void Main() { try { int hr = 0; byte[] gData = null; int gSize = 0; hr = GetData(ref gData, ref gSize); Console.WriteLine(gSize); for (int i = 0; i < gSize; i++) Console.WriteLine((char)gData[i]); } catch (Exception p) { Console.WriteLine(p.ToString()); } }
When I run the C # code, an AccessViolationException occurs in the GetData function, which is an exception sign in C ++ code, however, after the code snippet, C ++ works fine without any errors.
int _tmain(int argc, _TCHAR* argv[]) { unsigned char* data = NULL; int size = NULL; GetData(&data, &size); printf("%d", size); for (int i = 0; i < size; i++) printf("%c,", data[i]); return 0; }
If you compare the C # main and C ++ _tmain , they are almost the same, so can I be wrong?
source share