Accessing strings in c++ from c#

Scenario; You may have some c++ code you wish to output string data to be used in a c# application.

#include <stdio.h>
#include <string.h>

extern "C"
{
	__declspec(dllexport) int GetString(char* buf,int n)
	{
		strncpy(buf,"my string in cpp", n);
		return 0;
	}
}
using System.Runtime.InteropServices;

[DllImport("mycppdll.dll", CallingConvention = CallingConvention.Cdecl)]
static extern int GetString(StringBuilder buffer, int capacity);

void csharp(){
StringBuilder sb = new StringBuilder(1000);
GetString(sb, sb.Capacity);
string mycppstring = sb.toString();
}

0 comments