Click here to Skip to main content
Click here to Skip to main content
Go to top

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

, 1 Nov 2006
Rate this:
Please Sign up or sign in to vote.
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:

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

I have an interface which looks like this:

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

And my main class is:

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:

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:

[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)

Share

About the Author

shinilkp
Web Developer
Germany Germany
No Biography provided

Comments and Discussions

 
QuestionCalling C# dll form C++ exe PinmemberDineshKrish25-Jun-14 23:44 
QuestionC++ compilation error (Visual Studio 2010) Pinmembercharles9228-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 Pinmembera ahole26-Jun-11 16:35 
Generalcan you send a string/struct to the C# dll from C++ Pinmemberlonojohnson18-May-11 6:07 
GeneralRe: can you send a string/struct to the C# dll from C++ PinmemberRicky Gai29-Oct-13 22:18 
GeneralFound a not reported bug (with solution) Pinmemberbrian enno13-Jun-10 8:36 
GeneralError Message Pinmemberp0o0q1-Oct-09 22:51 
GeneralRe: Error Message [modified] PinmemberStellar Developer4-Jun-10 13:31 
GeneralRe: Error Message Pinmemberchinki150111-Oct-10 9:12 
GeneralCalling a C# dll that returns an array of double to C++ PinmemberMember #177489114-Feb-07 19:40 
Questionthe hr is not created, and everything goes ok, the building, debuging, there is a tlh and tli file ? Pinmemberpetrukon21-Dec-06 4:44 

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.140916.1 | Last Updated 2 Nov 2006
Article Copyright 2006 by shinilkp
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid