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 Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.