4

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?

7
  • What's the message on the exception? Also, what is the declaration of the unmanaged function? Commented Sep 27, 2011 at 13:52
  • 2
    is this helpful? Commented Sep 27, 2011 at 14:37
  • Thanks, mtijn, that helped. Solved by using IntPtr structures representing the strings to be marshaled. Commented Sep 27, 2011 at 15:01
  • This works fine when I try it, no manual marshaling required. There is a nasty flaw in the approach though, the native code has no way to tell how large the array is. An extra argument is required. Commented Sep 27, 2011 at 15:27
  • What version of Windows are you using? Is this Windows CE or something like that? Commented Sep 27, 2011 at 16:14

1 Answer 1

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)

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.