在这串编组结构时的PInvoke错误 [英] PInvoke error when marshalling struct with a string in it

查看:116
本文介绍了在这串编组结构时的PInvoke错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C ++结构

struct UnmanagedStruct
{
   char* s;
   // Other members
};

和一个C#结构

struct ManagedStruct {
   [MarshalAs(UnmanagedType.LPStr)]
   string s;
   // Other members
}



C ++库自曝

the C++ library exposes

extern "C" UnmanagedStruct __declspec(dllexport) foo( char* input );

和它是进口同类

  [DllImport("SomeDLL.dll", CharSet = CharSet.Ansi)]
  static extern ManagedStruct foo( string input );



然而,当我调用这个函数,我得到

However when I call this function I get

MarshalDirectiveException了未处理

MarshalDirectiveException was unhandled

方法的类型签名不是PInvoke的兼容。

Method's type signature is not PInvoke compatible.

问题是,此函数调用如果删除的char * S和从结构字符串s的工作。

The thing is, this function call works if I remove the char* s and the string s from the structs.

推荐答案

对于这种类型的情况下,不要使用直接的String。相反,切换到成为一个IntPtr值和使用Marshal.PtrToStringAuto / ANSI / UNI适当的类型。在这种情况下,由于您的本机代码使用的char * ,PtrToStringAnsi是最好的选择。

For this type of scenario, do not use a String directly. Instead switch the type to be an IntPtr value and use Marshal.PtrToStringAuto/Ansi/Uni as appropriate. In this case, since your native code uses char*, PtrToStringAnsi is the best choice.

struct ManagedStruct {
  IntPtr s;
  public string sAsString { get { return Marshal.PtrToStringAnsi(s); } }
}

这篇关于在这串编组结构时的PInvoke错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆