Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Marshalling a const char* return value from dll [duplicate]

Tags:

c#

dllimport

I have a function in a dll with the following identifier.

const char* function(void)

The DLL allocates the string on the heap and expects it only to be read. I have tried the following to import the function but am getting an access violation

[DllImport("great.dll", CharSet = CharSet.Ansi, 
                        CallingConvention = CallingConvention.Cdecl)
]
public static extern string function();

How do I handle this properly

Error message:

System.AccessViolationException: 'Attempted to read or write protected memory. This is often an indication that other memory is corrupt.'

like image 853
kealist Avatar asked Nov 18 '25 12:11

kealist


1 Answers

Regarding the text in the question ""With other functions with the same parameter type, I have been able to use [MarshalAs(UnmanagedType.LPStr)] to handle it, but this will not work for return values."

quoting this from https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.marshalasattribute?view=netframework-4.7

//Applied to a return value.
[return: MarshalAs(UnmanagedType.LPWStr)]
    public String GetMessage()
    {
        return "Hello World";
    }

update: keeping this in case it is helpful for others searching about "MarshalAs" and return values, since the author of the question has already solved their issue as they comment above

like image 161
George Birbilis Avatar answered Nov 21 '25 04:11

George Birbilis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!