Marshaling list string from C++ to C#

TaiDH 21 Reputation points
2021-12-25T06:45:04.277+00:00

Hi guys, now i studying the way to marshalling list string in struct from C++ to C#. The structure of struct same like:
In C++:
struct A
{
wchar_t Name[24][16];
}

in C#:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
Class A
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst =24 * 4)]
public string[] Name= new string[24];
}

What is the best way to solve this case ?

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,196 questions
C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,518 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 111.7K Reputation points
    2021-12-25T09:11:55.787+00:00

    Try these definitions:

    [StructLayout( LayoutKind.Sequential, CharSet = CharSet.Unicode )]
    struct Name
    {
        [MarshalAs( UnmanagedType.ByValTStr, SizeConst = 16 )]
        public string Value;
    }
    
    [StructLayout( LayoutKind.Sequential, CharSet = CharSet.Unicode )]
    class A
    {
        [MarshalAs( UnmanagedType.ByValArray, SizeConst = 24 )]
        public Name[] Name = new Name[24];
    }
    
    [DllImport( @"MyDll.dll", CallingConvention = CallingConvention.StdCall )]
    extern static void Test1( [In, Out] A a );
    
    . . .
    
    A a = new A( );
    a.Name[1].Value = "str1";
    
    Test1( a );
    

    ā€ƒ

    // In C++:
    
    struct A
    {
        wchar_t Name[24][16];
    };
    
    extern "C" __declspec( dllexport ) void __stdcall Test1( A * a ) 
    {
        wcscpy_s( a->Name[2], L"str2" );
    }
    

0 additional answers

Sort by: Most helpful