Hi,
Having a bit of a problem here that has stumped a few of us at the office.
Background:
We’re using some functions in an external DLL file, and have across some problems. The DLL in question, let’s call it ‘foo.dll’ is dependent on another dll ‘bar.dll’. I’ve managed to make this work by first calling a function in bar.dll. However, problems arise when calling one specific function in foo.dll. The code in C++ looks something like this:
char *CALLBACK Keys(const char *model, char *mem, int *max, int lang)
model is the model I want to input, mem is a char array with its size set to whatever max size we want, max is said max value, and the last in language.
To access it, I use
[DllImport("Foo", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi, EntryPoint = "Keys")]
private static extern string Keys(IntPtr model, IntPtr mem, IntPtr max, int lang);
and
lock (this)
{
const int max = 45000;
string allocMem = new string(' ', max);
byte[] allocMemBytes = Encoding.UTF8.GetBytes(allocMem);
bXml = Encoding.UTF8.GetBytes(xmlString);
GCHandle maxGC = GCHandle.Alloc(max, GCHandleType.Pinned);
GCHandle memGC = GCHandle.Alloc(allocMemBytes, GCHandleType.Pinned);
GCHandle bXmlGC = GCHandle.Alloc(bXml, GCHandleType.Pinned);
string output = Keys(bXmlGC.AddrOfPinnedObject(), memGC.AddrOfPinnedObject(), maxGC.AddrOfPinnedObject(), 0);
memGC.Free();
maxGC.Free();
bXmlGC.Free();
}
This works in a separate C# console application. The dll is supposed to spit out a xml file, which it does. However, when I try to call the same function from my unity application, the Unity Editor simply exits and crashes. I can’t even catch an exception if I try to.
I’ve managed to snatch the following crash log when building a standalone Unity3D player:
foo.dll caused an Access Violation (0xc0000005) in module foo.dll at 001b:02b96630.
and
Read from location 00000050 caused an access violation.
I can access another function in the dll just fine, the only difference that this function writes the xml to the harddrive, instead of the memory. Anyone with a clue why it works only when I run the code in my console application, and what I need to do to get it working in Unity?