Skip to content

Instantly share code, notes, and snippets.

@esskar
Created September 24, 2012 23:22
Show Gist options
  • Save esskar/3779066 to your computer and use it in GitHub Desktop.
Save esskar/3779066 to your computer and use it in GitHub Desktop.
passing char*[] from c++ dll Struct to c#
#include <stdio.h>
#include <Windows.h>
struct Name
{
char FirstName[100];
char LastName[100];
char *Array[3];
};
extern "C" __declspec(dllexport) void __cdecl GetName(struct Name *name)
{
strncpy_s(name->FirstName, "FirstName", sizeof(name->FirstName));
name->Array[0] = "Foo 0";
name->Array[1] = "Foo 1";
name->Array[2] = "Foo 2";
}
extern "C" __declspec(dllexport) void __cdecl Hello()
{
printf("Hello\n");
}
using System;
using System.Runtime.InteropServices;
namespace TestApp
{
class Program
{
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct Name
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 100)]
public string FirstName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 100)]
public string LastName;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
public string[] Array;
};
[DllImport("TestDll.dll")]
public static extern void GetName(ref Name name);
[DllImport("TestDll.dll")]
public static extern void Hello();
static void Main(string[] args)
{
Hello();
var name = new Name();
GetName(ref name);
Console.WriteLine(name.FirstName);
foreach (var s in name.Array)
Console.WriteLine(s);
}
}
}
@rlcaldas
Copy link

Thanks. I am beginning in C++.. This saved my life ;-)

@Dorthyn
Copy link

Dorthyn commented Sep 7, 2017

[DllImport("TestDll.dll", CallingConvention = CallingConvention.Cdecl)]
should be added into the code.

@mcka-dev
Copy link

mcka-dev commented Mar 6, 2018

It does not work for me. E2440 Cannot convert 'const char [5]' to 'char *' in 14 line (

@brayanc9805
Copy link

Thank You!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment