Rendijs S
Rendijs S

Reputation: 365

Passing an array of strings from managed C# to unmanaged function using P-Invoke

Is it possible to pass a string array from managed C# to an unmanaged function using P-Invoke?

This works fine:

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

While this:

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

fails with

Unhandled exception: System.NotSupportedException: NotSupportedException

I have tried using MarshalAs with no luck ([MarshalAs(UnmanagedType.LPArray, ArraySubType=UnmanagedType.LPWStr)] String[] dataToLoadArr)

Is it possible to pass string arrays this way?

Upvotes: 4

Views: 2464

Answers (1)

Ani
Ani

Reputation: 10896

[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)

This works fine in my OpenCL library, OpenCL.NET (http://openclnet.codeplex.com/SourceControl/changeset/view/94246#1251571). Note that I am passing in the count using SizeParamIndex as well.

Upvotes: 1

Related Questions