Passing a string array in c programming with C #

I call the unmanaged C programming code from the C # .Net control code. But I cannot pass a string array as a parameter to a function from .Net Function in C:

dllmain(const int argc, const char *argv[]){} 

Please help me how can I call this function with C Sharp.Net

Thanks.

+2
source share
2 answers

Add the following attributes to the argv attribute when declaring a function in .net:

 [In][MarshalAsAttribute(UnmanagedType.LPArray, ArraySubType=UnmanagedType.LPStr)] 

You must also add the CharSet=CharSet.Unicode property to the CharSet=CharSet.Unicode attribute applied to the external function.

+1
source

Here's how you can do it:

C # code:

  • Declare the C function you want to call from C #

     [DllImport("<DLL_File_Name>.dll", CharSet = CharSet.Auto, EntryPoint = "dllmain", ExactSpelling = false, CallingConvention = CallingConvention.StdCall)] public static extern void dllmain(ref string str1); 
  • Define a string

     [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 100)] public string str1; 
  • Call C function from C # code

      dllmain(ref str1); 

C code:

  • Function prototype

     __declspec(dllexport) void __stdcall dllmain(char *str1); 
  • Function Definition

     void__stdcall dllmain(char *str1) { : } 

Hope this will be helpful for you. :-)

+1
source

Source: https://habr.com/ru/post/1336892/


All Articles