[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now


Passing strings from c# application to c++ dll

Posted on 2007-07-31
Medium Priority
Last Modified: 2012-08-14
Im trying to create a dll in c++ that i can reference from a c# application.  My problem is that i am new to c++ and am just starting the grasp the concepts behind all the different types of strings.  I have built a managed class in c++ and linked it fine in c#.  it worked for passing ints and doubles as parameters but i cant figure out how to pass a string as a parameter or likewise return a string.  
Any help is appreciated, thank you.
Question by:drezdrez
LVL 96

Expert Comment

by:Bob Learned
ID: 19602641
It all depends on how the strings are defined in C++, as to what type of string marshalling that you are going to need.

LVL 86

Accepted Solution

jkr earned 2000 total points
ID: 19602800
http://msdn.microsoft.com/msdnmag/issues/02/08/CQA/ pretty much targets this issue. You could do that like

C++ DLL ("returnstring.dll"):  

#include <windows.h>
#include <tchar.h>

int GetString(LPSTR buf, int nMaxCount)
      TCHAR* pszText = _T( "Hi from unmanaged code");
      int nLen = _tcslen(pszText);

      if (nLen < nMaxCount)

         return nLen;

      return 0;


using System.Text; // for StringBuilder
public class ReturnStringDll{
  public static extern int GetString(StringBuilder buf, int nMaxCount);

StringBuilder cb = new StringBuilder(256);
ReturnStringDll.GetString(sb, sb.Capacity);

That works for just displaying a string on the C++ side also.

Author Comment

ID: 19603066
Thank you jkr,  
I've got this working and its put me back int he right direction.

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
This article will inform Clients about common and important expectations from the freelancers (Experts) who are looking at your Gig.
In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …
Simple Linear Regression

868 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question