Click here to Skip to main content
15,867,686 members
Articles / Programming Languages / C#

Call C# code from C++ and read an array of struct which contains strings

Rate me:
Please Sign up or sign in to vote.
4.05/5 (13 votes)
1 Nov 2006CPOL2 min read 134.3K   5.3K   28   17
How to call C# code from C++ and read an array of struct which contains strings.

Introduction

My C++ code was trying to read an array of struct which contains string data in C#. To my surprise, I found that a struct array which contains only integers is very easy to get, but if you have a string in the array, you need to do some more things. I searched on Google, and a lot of people were talking about the same problem and getting an exception which says, "Old format or invalid type library". But no where was I able to find the answer, and since I was able to solve the problem myself, I am publishing the solution here.

Basic Ideas

I have a C# DLL which contains a struct; let's say:

C#
public struct MyStruct
{
    public string name;
    public string surname;
    public int age;
}

I have an interface which looks like this:

C#
public interface ITest
{
    MyStruct[] GetData        
    {
        get;
    }
}

And my main class is:

C#
public class Test : ITest
{
    MyStruct[] st = new MyStruct[2];
    public Test()
    {
        st[0].name = "abc";
        st[0].surname = "def";
        st[0].age = 10;
 
        st[1].name = "qwe";
        st[1].surname = "rty";
        st[1].age = 20;
    }
 
    public MyStruct[] GetData
    {
        get
        {
            return st;
        }
    }         
}

Now build the DLL. Then, from the Visual Studio ommand prompt, type type "regasm MyInterOp.dll /tlb:MyInterOp.tlb". Have look at the tlb using OleViewer. Find the tag MyStruct. It will have an LPSTR.

Now create a console application in C++ like this:

C++
HRESULT hr = CoInitialize(NULL);
ITest* pTest = NULL;
hr = CoCreateInstance(__uuidof(Test),NULL, 
       CLSCTX_INPROC_SERVER,__uuidof(ITest),(void**)&pTest);
 
MyInterOp::MyStruct HUGEP *pBSTR;
 
hr = SafeArrayAccessData(pTest->GetData, (void HUGEP* FAR*)&pBSTR);
        
printf("Name: %S \n",pBSTR[0].name);
printf("SurName: %S \n",pBSTR[0].surname);
printf("Age: %d \n",pBSTR[0].age);
 
printf("Name: %S \n",pBSTR[1].name);
printf("SurName: %S \n",pBSTR[1].surname);
printf("Age: %d \n",pBSTR[1].age);

When you run this application, it will give you an exception. If you debug it, you can see that the HRESULT is "-2147319783" which means "Old format or invalid type library." So LPSTR is not going to work for us.

Solution

How can we solve this issue? Make your struct look like this:

C#
[StructLayout(LayoutKind.Sequential)]
public struct MyStruct
{
    [MarshalAs(UnmanagedType.BStr)]
    public string name;
    [MarshalAs(UnmanagedType.BStr)]
    public string surname;
    public int age;
}

Register the DLL once again and look at the tlb. See that now it is BSTR instead of LPSTR.

Now run the C++ Console application.

Requirements

In order to run the mz test application.

  1. Open the C# solution in a VS 2005.
  2. Build the solution.
  3. Use regasm to register the tlb.
  4. Open the C++ dsw in VS 6.
  5. In the #import section, refer to the appropriate location in your machine. "#import "E:\MyTestApps\TestInterOp\Debug\MyInterOp.tlb"".
  6. Run the Console application and that's it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
Germany Germany
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionException thrown: read access violation. pTest was nullptr. Pin
Member 1499350715-Nov-20 5:43
Member 1499350715-Nov-20 5:43 
QuestionI had C# DLL making SOAP calls - this requires setting SecurityProtocol Pin
oniDino6-Feb-20 9:47
oniDino6-Feb-20 9:47 
QuestionCan any one explain why LPSTR doesn't work and why we use BStr Pin
Member 1406468516-Aug-19 2:39
Member 1406468516-Aug-19 2:39 
QuestionCalling C# dll form C++ exe Pin
DineshKrish25-Jun-14 23:44
DineshKrish25-Jun-14 23:44 
AnswerRe: Calling C# dll form C++ exe Pin
Daniel Kamisnki18-Sep-18 15:35
Daniel Kamisnki18-Sep-18 15:35 
GeneralRe: Calling C# dll form C++ exe Pin
Member 139774068-Jan-20 8:21
Member 139774068-Jan-20 8:21 
GeneralRe: Calling C# dll form C++ exe Pin
Daniel Kamisnki8-Jan-20 10:20
Daniel Kamisnki8-Jan-20 10:20 
I figured out the issue. The dll needs to be registered in the client machine. I think you can do it using regasm, but I achieved it using a custom registration application that updates the client machine registry with the proper information.

QuestionC++ compilation error (Visual Studio 2010) Pin
charles9228-Aug-13 18:48
charles9228-Aug-13 18:48 
QuestionHow about having Action delegate in c# and the action delegate method in c++ how could you code passing the action delgate method to action delegate Pin
a ahole26-Jun-11 16:35
a ahole26-Jun-11 16:35 
Generalcan you send a string/struct to the C# dll from C++ Pin
lonojohnson18-May-11 6:07
lonojohnson18-May-11 6:07 
GeneralRe: can you send a string/struct to the C# dll from C++ Pin
Ricky Gai29-Oct-13 22:18
Ricky Gai29-Oct-13 22:18 
GeneralFound a not reported bug (with solution) Pin
brian enno13-Jun-10 8:36
brian enno13-Jun-10 8:36 
GeneralError Message Pin
p0o0q1-Oct-09 22:51
p0o0q1-Oct-09 22:51 
GeneralRe: Error Message [modified] Pin
Stellar Developer4-Jun-10 13:31
Stellar Developer4-Jun-10 13:31 
GeneralRe: Error Message Pin
chinki150111-Oct-10 9:12
chinki150111-Oct-10 9:12 
GeneralCalling a C# dll that returns an array of double to C++ Pin
Member 177489114-Feb-07 19:40
Member 177489114-Feb-07 19:40 
Questionthe hr is not created, and everything goes ok, the building, debuging, there is a tlh and tli file ? Pin
petrukon21-Dec-06 4:44
petrukon21-Dec-06 4:44 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.