Why can't I return a char* string from C++ to C# in a Release build?

后端 未结 5 901
梦如初夏
梦如初夏 2021-01-31 10:07

I\'m attempting to call the following trivial C function from C#:

SIMPLEDLL_API const char* ReturnString()
{
    return \"Returning a static string!\";
}
         


        
5条回答
  •  长情又很酷
    2021-01-31 10:53

    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();
    

提交回复
热议问题