【问题标题】:Passing an array of strings from managed C# to unmanaged function using P-Invoke使用 P-Invoke 将字符串数组从托管 C# 传递到非托管函数
【发布时间】:2012-02-14 03:24:59
【问题描述】:

是否可以使用 P-Invoke 将字符串数组从托管 C# 传递到非托管函数?

这很好用:

[DllImport("LibraryName.dll")]
private static extern void Function_Name(string message);

此时:

[DllImport("LibraryName.dll")]
private static extern void Function_Name(string[] message);

失败

未处理的异常:System.NotSupportedException: NotSupportedException

我尝试过使用MarshalAs,但没有成功([MarshalAs(UnmanagedType.LPArray, ArraySubType=UnmanagedType.LPWStr)] String[] dataToLoadArr)

这种方式可以传递字符串数组吗?

【问题讨论】:

  • 异常信息是什么?另外,非托管函数的声明是什么?
  • this 有用吗?
  • 谢谢,mtijn,这有帮助。通过使用表示要编组的字符串的 IntPtr 结构来解决。
  • 我尝试时效果很好,不需要手动编组。但是,这种方法有一个严重的缺陷,本机代码无法判断数组有多大。需要一个额外的参数。
  • 您使用的是什么版本的 Windows?这是 Windows CE 还是类似的东西?

标签: c# .net pinvoke marshalling unmanaged


【解决方案1】:
[DllImport(Library)]
private static extern IntPtr clCreateProgramWithSource(Context context,
                                                       cl_uint count,
                                                       [In] [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPStr, SizeParamIndex = 1)] string[] strings,
                                                       [In] [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.SysUInt, SizeParamIndex = 1)] IntPtr[] lengths,
                                                       out ErrorCode errcodeRet);
public static Program CreateProgramWithSource(Context context,
                                                 cl_uint count,
                                                 string[] strings,
                                                 IntPtr[] lengths,
                                                 out ErrorCode errcodeRet)

这在我的 OpenCL 库 OpenCL.NET (http://openclnet.codeplex.com/SourceControl/changeset/view/94246#1251571) 中运行良好。请注意,我也使用 SizeParamIndex 传递计数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-18
    • 2011-09-15
    • 1970-01-01
    • 2013-03-06
    • 1970-01-01
    • 2010-11-06
    • 1970-01-01
    • 2013-02-09
    相关资源
    最近更新 更多