I\'m attempting to call the following trivial C function from C#:
SIMPLEDLL_API const char* ReturnString()
{
return \"Returning a static string!\";
}
It's also possible to do that with a custom Marshaler:
class ConstCharPtrMarshaler : ICustomMarshaler
{
public object MarshalNativeToManaged(IntPtr pNativeData)
{
return Marshal.PtrToStringAnsi(pNativeData);
}
public IntPtr MarshalManagedToNative(object ManagedObj)
{
return IntPtr.Zero;
}
public void CleanUpNativeData(IntPtr pNativeData)
{
}
public void CleanUpManagedData(object ManagedObj)
{
}
public int GetNativeDataSize()
{
return IntPtr.Size;
}
static readonly ConstCharPtrMarshaler instance = new ConstCharPtrMarshaler();
public static ICustomMarshaler GetInstance(string cookie)
{
return instance;
}
}
And use it like this:
[DllImport("SimpleDll")]
[return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(ConstCharPtrMarshaler))]
public static extern string ReturnString();