When calling an unmanaged Dll from a c# application I get an AccessViolationException
. The strange thing is that the exported function has no arguments, so the problem is not in the Marshalling of data. The function gets no argument and just returns an integer. Also note that calling convention is not an issue. An identical function with the same zero arguments and integer return value (but different name) works just fine. What are the remaining candidate reasons that such a call could cause this exception considering the fact that marshalling and calling convention is ruled out?
UPDATE: The dll function is correct because if called from other unmanaged code through plain linking, then it works perfectly.
UPDATE 2: Everything is compiled and run on 32 bit. I tried Win XP SP2 and Vista. Here is an interesting fact: On Vista Systems it works like a charm. On XP it fails.
UPDATE 3: I didnt get the source code but I learned what essentially this dll does, so i tried to reproduce the problem with my own dll. Here is the story: The original dll is some kind of a wrapper to ei.lib (Erlang's c interface library). It exports some helper funcs. So to reproduce the problem I have made a wrapper dll around ei.lib which exports only one function, namely "test()". I did that so I wouldnt mess with marshalling and stuff. I wanted just to test an initialization, connecting and sending a message. So this test() func of my dll just calls ei_connect_init()
, then ei_connect()
and finaly ei_reg_send()
, with arguments hardcoded inside. The problem is that if I call this dll and use the test() function from another unmanaged code, it works ok. Message is sent. But when I call it from c# through DllImport then it works only on Vista. Not on XP. On XP it fails with a AccessViolationException on the .net layer. I ve tried to trace down the problem and I see that from inside my dll, any call to ei_connect()
, or any attempt to read erl_errno
(these are defined in ei.lib) when running on XP and being called by managed code result in trying to read or write protected memory so the app crashes. It cant be something trivial since it works on Vista and it works when called by unmanaged code.