You need to use
Marshaling[
^].
C++ takes a string as the raw ASCII (for
char *
) data, followed by a single byte with the value of
0
. Not sure how C# stores it's string, but I bet there is a length stored in there somewhere.
So, a very simple example:
MYDLL.cpp:
#include <Windows.h>
#include <stdio.h>
extern "C" __declspec(dllexport) int init_set(char *sz) {
printf("%s\n", sz);
return 0;
}
BOOL APIENTRY DllMain(HMODULE hModule, DWORD nReason, LPVOID lpReserved) {
return TRUE;
}
and the C# file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace CS_CLI
{
class Program
{
[DllImport("MYDLL.dll")]
public static extern int init_set(IntPtr s);
static void Main(string[] args)
{
String str = "I am a managed String";
IntPtr ptrCString = (IntPtr)Marshal.StringToHGlobalAnsi(str);
init_set(ptrCString);
Marshal.FreeHGlobal(ptrCString);
}
}
}