I have a main program and DLL both written in C (not C++) and working fine on Linux with gcc and Windows with Borland C. I need to get this to work in Microsoft C as well as I need a 64 bit version.
I have imported the two elements into Visual Studio 2010 Express as Win32 projects set to compile as C. Everything compiles fine and runs up to the point when it attempts to use the callback function, raising an access violation exception.
The main program contains a function declared as
String * AllocString(int len, char * s);
where the String datatype is a simple structure.
The AllocString function works correctly from within the main program.
The address of this function is passed to the DLL as an argument when calling the first DLL function and saved for later use. I have tried passing this as an argument declared as the full function definition for AllocString and also simply as a long integer of the function address. Both should, of course, be the same as far as the low level stack operations go.
I have printed the function address on both sides of this call interface and it arrives correctly in the DLL.
At some later point the DLL then does
s = AllocString(11, "Hello world");
I can see that it does the function call but it never executes the first statement in the function in the main program. Instead, it causes a fatal error. The Windows event log shows an exception code of xC0000005 (access violation) with the fault offset exactly equal to the callback function address.
I have read countless web postings on callbacks and cannot see anything wrong. And, remember, this works fine in Borland C or with gcc on Linux.
Have I missed some special incantation needed in Microsoft C?
This could be due to a wrong calling convention or due to linking CRT statically (this is not recommended, as you have 2 instances of CRT running which sees different memory addresses). Use CRT dinamically.