Pointers in C# to Retrieve Reference From DllImport Function

后端 未结 3 849
滥情空心
滥情空心 2021-01-23 01:12

I am referencing a DLL in my C# project as follows:

[DllImport(\"FeeCalculation.dll\", CallingConvention = CallingConvention.StdCall,
           CharSet = CharSe         


        
3条回答
  •  借酒劲吻你
    2021-01-23 01:50

    The char* parameters in this case are not strings but pointers to chunks of raw bytes representing the data. You should marshal your parameters as instances of the IntPtr type, in conjunction with Marshal.AllocHGlobal to create a chunk of memory and then Marshal.PtrToStructure to convert that block of memory into a usable .NET type.

    As an example:

    [StructLayout(LayoutKind.Sequential)]
    struct MyUnmanagedType
    {
        public int Foo;
        public char C;
    }
    
    IntPtr memory = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(MyUnmanagedType)));
    
    try
    {
        FeeCalculation(memory);
    
        MyUnmanagedType result = (MyUnmanagedType)Marshal.PtrToStructure(
            memory, typeof(MyUnmanagedType));
    }
    finally
    {
        Marshal.FreeHGlobal(memory);
    }
    

提交回复
热议问题