简体   繁体   中英

Access Violation when returning a value calling a C++ dll function from C#

I'm trying to make a call from C# to a c++ function in a DLL. One argument of this function is a pointer to a short type variable.

I'm not doing any fancy data structure, or unknown-sized variables. Just a simple short value.

When the DLL c++ function tries to modify the value of this variable, it gives an "Unmanaged exception 0xC0000005: Access Violation".

I cannot modify the DLL source (it's used in other projects and I cannot touch it, though I have the source code to debug it)

Code of the c++ DLL function (please note the "//this line provokes the exception" comment line in the code)

// declaration
virtual TestFunction(short __RPC_FAR *sRet) = 0;

// definition
STDMETHODIMP CABTest::TestFunction(short *sReturnValue)
{
    //some
    //calculations
    //here
    *sReturnValue = 1; //this line provoques the exception
    return 0;
}

C# code invoking the DLL

[DllImport("test.dll", SetLastError = true, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
static extern short TestFunction(ref short sReturn);

short sMyValue = 0;
TestFunction(ref sMyValue);

I would expect sMyValue to value 1, as the reference I'm passing is a straight short type (not a fancy data struct) but I only get an app crash (the above exception).

What can I do in the C# code to avoid this problem? All I've seen searching for similar questions required rewriting the C++ functions (changing "short *sReturnValue" for "short **sReturnValue" but I cannot touch the original DLL source code.

I think I will write a wrapper.dll that invokes the test.dll but I was wondering if there was any direct and faster solution.

I created an instance as @PaulMcKenzie suggests and it's working fine. I erroneously thought that I could just grab the DLL and use the calculation functions needed but I guess I couldn't. Just leaving this answer for others that might make the same mistake.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM