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();
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s