Click here to Skip to main content
15,886,799 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am just playing around with some PInvoke stuff. I am getting an AcessViolationException error when I am trying to run the app. This is my C++ code"

C++
extern "C"
{
  __declspec(dllexport) double DecodeLatitude(string s, bool mustFlip)
  {
    bitset<28> hh(s);
    if (mustFlip) {hh.flip();}
    return hh.to_ulong();
  }
}


And here is my C# code that calls this:

C#
[DllImport("BinaryConvert.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern double DecodeLatitude([MarshalAs(UnmanagedType.BStr)]string s, [MarshalAs(UnmanagedType.I1)]bool mustFlip);

static void Main()
        {
            double a = DecodeLongitude("001000110010001110111001100", false);
            Console.ReadLine();
        }


Can someone help a beginner out :P
Posted
Updated 28-Nov-11 10:19am
v2

1 solution

You need to check the definitions for the different types between C# and C++. For example, UnmanagedType.LPStr as defined here[^], is a pointer to a null-terminated array of ANSI characters. This equates to a char* in C++, not a string.

Similarly, you are returning an unsigned long (hh.to_ulong()) to a C# call that expects a Double value to be returned.
 
Share this answer
 
Comments
DominicZA 28-Nov-11 16:20pm    
Please see updated code. The issue is definitely with the string. I have tested everything else, but it only crashes when I parse it a string.
Richard MacCutchan 29-Nov-11 4:48am    
Did you read my comments? Your function parameter in the C++ code needs to match the type of the parameter in the C# code. You are not passing a std::string from your calling method, nor is your C++ function returning a Double.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900