Created
September 24, 2012 23:22
-
-
Save esskar/3779066 to your computer and use it in GitHub Desktop.
passing char*[] from c++ dll Struct to c#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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"); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
Thanks. I am beginning in C++.. This saved my life ;-)
[DllImport("TestDll.dll", CallingConvention = CallingConvention.Cdecl)]
should be added into the code.
It does not work for me. E2440 Cannot convert 'const char [5]' to 'char *'
in 14 line (
Thank You!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
good one.