How to call an external API function that takes a struct containing arrays as its parameter?

Discussion in 'ASP .Net' started by Robert Rossney, Sep 1, 2003.

  1. I'm working on a .NET application interoperates with a legacy application.
    This application exposes an API through a single function call that takes a
    great big struct full of string data as its argument.

    In VB6, I can call the API by using these declarations:

    Public Declare Sub MyApi Lib "MyApi.DLL" (buf As BUFFER_TYPE)

    Public Type BUFFER_TYPE
    foo As String * 50
    bar(49) As String * 100
    status As int
    End Type

    I'm trying to write the equivalent C#.Net code, and I *think* it should look
    something like this:

    [StructLayout (LayoutKind.Sequential)]

    internal struct barString
    [MarshalAs( UnmanagedType.AnsiBStr, SizeConst=100)]
    internal string data;

    internal struct buffer
    [MarshalAs( UnmanagedType.AnsiBStr, SizeConst=50 )]
    internal string foo;
    [MarshalAs( UnmanagedType.ByValArray, SizeConst=49)]
    internal barString bar[];
    [MarshalAs (UnmanagedType.I2)]
    internal int status;

    private static extern void MyApi(buffer buf);

    That is, in order for me to create a 49-element array of 100-byte strings
    (bar), I first need to create a struct that's a 100-byte string, and then I
    need to create an array of that struct that is dimensioned to 49 elements.

    This seems awfully complicated. (Also, the real data structure is much more
    complex than this, containing many arrays.) Is this really the right way to
    do this?

    In addition, this code:

    buffer buf;
    foreach (barString oneBar in
    { = "";

    fails in the assignment statement with the message "The left-hand side of an
    assignment must be a variable, property, or indexer." This leads me to
    suspect that I'm not using structs properly, but for the life of me I can't
    see why not.

    Any ideas and pointers would be much appreciated. Thanks.

    Bob Rossney
    Robert Rossney, Sep 1, 2003
    1. Advertisements

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.

Share This Page