Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling unmanaged function char returns char *

I have a function in unmanaged C/C++ code (dll) that returns a structure containing a char array. I created C# struct to receive this return value uppon calling the function. And uppon calling this function i get 'System.Runtime.InteropServices.MarshalDirectiveException'

This is C declaration:

typedef struct T_SAMPLE_STRUCT {
int num;
char text[20];
} SAMPLE_STRUCT;

SAMPLE_STRUCT sampleFunction( SAMPLE_STRUCT ss );

This is C# declaration:

struct SAMPLE_STRUCT
{
    public int num;
    public string text;
}

class Dllwrapper
{
    [DllImport("samplecdll.dll")]
    public static extern SAMPLE_STRUCT sampleFunction(SAMPLE_STRUCT ss);

}

I am using 1-byte ASCII.

Does anyone has a hint or a solution on how to do this?

like image 830
Mita Avatar asked Apr 13 '26 08:04

Mita


1 Answers

The trick to converting a C array member is to use the MarshalAs(UnmanagedType.ByValTStr). This can be used to tell the CLR to marshal the array as an inlined member vs. a normal non-inlined array. Try the following signature.

[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, CharSet=System.Runtime.InteropServices.CharSet.Ansi)]
public struct T_SAMPLE_STRUCT {

    /// int
    public int num;

    /// char[20]
    [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst=20)]
    public string text;
}

public partial class NativeMethods {

    /// Return Type: SAMPLE_STRUCT->T_SAMPLE_STRUCT
    ///ss: SAMPLE_STRUCT->T_SAMPLE_STRUCT
    [System.Runtime.InteropServices.DllImportAttribute("<Unknown>", EntryPoint="sampleFunction")]
public static extern  T_SAMPLE_STRUCT sampleFunction(T_SAMPLE_STRUCT ss) ;

}

This signature is brought to you by the PInovke Interop Assistant (link) available on CodePlex. It can automatically translate most PInvoke signatures from native code to C# or VB.Net.

like image 105
JaredPar Avatar answered Apr 14 '26 21:04

JaredPar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!