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.'
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With