user888270
user888270

Reputation: 631

Reading string from C# managed code to C++ wchar* [] getting AccessViolation

The question is easy, Want to read a string from managed C# code to my unmanaged C++ code in WCHAR* []. The C function is:

extern "C"  __declspec(dllexport) int __cdecl myfunc(int argc, WCHAR* argv[])

and in C# I imported the DLL:

[DllImport("mydll.dll", CharSet = CharSet.Auto, SetLastError = true, CallingConvention = CallingConvention.Cdecl)]
public static extern int myfunc(int argc, [MarshalAs(UnmanagedType.LPTStr)]  StringBuilder str);

I run, but when I tried to read the string in my C++ code I get AccessViolationException : Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

What is the correct way to do this and vice versa (i.e. passing a string from C++ unmanaged to C# managed code)?

Help Appreciated. Thanks

Upvotes: 0

Views: 2779

Answers (3)

Christoffer
Christoffer

Reputation: 12910

If you are using a WCHAR*, perhaps you should try marshalling as UnmanagedType.LPWStr instead to avoid passing half as much memory as expected?

The documentation on Default Marshaling for Strings should provide you with more details.

Upvotes: 0

Sagar Bhat
Sagar Bhat

Reputation: 121

I am not sure about C# to C++ but i can help you out in your C++ to C# problem.

Export the function from C++ code like this:

DllExport std::string MyFunction( std::string MyParameter) ;

This can be imported in your C# code as:

 [DllImport("DLLName.dll", EntryPoint = "MyFunction", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
    [return: MarshalAs(UnmanagedType.LPStr)]
    public static extern string MyFunction([System.Runtime.InteropServices.InAttribute()] [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPStr)] string MyParameter);

Now, in your C# code the function "MyFunction" will take in a string and return a string. You can then call MyFunction and the operations can be carried out.

Upvotes: 0

Vlad
Vlad

Reputation: 18633

It seems that your C function expects an array of strings, and you're passing a single string instead.

I haven't used P/Invoke myself, but this question might provide some insight.

Upvotes: 1

Related Questions