.net - Access violation when calling Delphi DLL from C# in a multi-threaded environment -
i calling dll function written in delphi xe2 c# using p/invoke. appears working when calls made sequentially single thread. however, when multiple threads calling function, c# host application throws system.accessviolationexception
seemingly @ random.
why code below trigger access violation , how fix this?
minimum delphi library code reproducing problem:
library pinvokeproblem; {$r *.res} uses windows, sysutils; procedure test(const testbyte: byte); stdcall; begin outputdebugstring(pwidechar(inttostr(testbyte))); end; exports test; end.
minimum c# host application code reproduce problem:
[dllimport( "pinvokeproblem.dll", callingconvention = callingconvention.stdcall, entrypoint = "test")] private static extern void test(byte testbyte); public static void main(string[] args) { (int = 1; <= 1000; i++) // more iterations = better chance fail { int threadcount = 10; parallel.for(1, threadcount, new paralleloptions { maxdegreeofparallelism = threadcount }, test => { byte byteargument = 42; test(byteargument); console.writeline(string.format("iteration {0}: {1}", test, byteargument)); }); } }
additional information:
platform x64 windows 7. c# host application built x86 in .net 4.0, delphi dll compiled 32-bit.
the library appears working ok when used in multi-threaded delphi host application.
an msvc version of dll function signature
extern __declspec(dllexport) void __stdcall test(char testbyte)
works fine c# host (which suggests somehow specific delphi).the code not fail if library function has no return value (
void
) , arguments.changing calling convention in both code
cdecl
did not help.
any ideas appreciated.
all have set ismultithread
true
(as first line in dll's main begin
..end
block) switch memory manager thread-safe mode:
ismultithread := true;
Comments
Post a Comment