cs0815
cs0815

Reputation: 17418

Invoke C/C++ code from C#

I usually use C# but have the pleasure to invoke a C method via C++. So I wrote a C++ wrapper like this:

The C++ header file looks like this:

#pragma once

using namespace System;

namespace CSharpToCPP {

    public ref class SomeWrapper
    {
        public:
        double ReturnValue();
    };
}

The C++ code looks like this:

double CSharpToCPP::SomeWrapper::ReturnValue()
{
    return 1;
}

This gives me dll which I can reference in C#. The working code in C# looks like this:

class Program
{
    static void Main(string[] args)
    {
        SomeWrapper Wrapper = new SomeWrapper();

        Console.WriteLine(Wrapper.ReturnValue());
    }
}

Now I would like to create some data in the C++ method ReturnValue and invoke the C method with this signature:

real_T get_value(const e_struct_T parameters, real_T temp)

Can someone please be so kind and point me in the right direction which explains what a const e_struct_T is and how to create such data? The C code was automatically generated and should take a structure with known content. I tried to define a structure in the header file like this:

struct Parameters{
    double x;
    int y;
    char z1;
    bool z2;
};

and then populate it with data like this:

Parameters Ps;
Ps.x = z2;
Ps.x = 2.0;

before invoking get_value like this:

get_value(Ps, 10.0);

This does not work. Thanks!

Upvotes: 1

Views: 436

Answers (1)

Felice Pollano
Felice Pollano

Reputation: 33272

You must search for an header file containing the definition of e_struct_t, include in the calling file, and use a variable of that type to pass to get_value; By the way, if the target method you want to call from C# is pure C, you probably should consider better using P/Invoke ( a tutorial here ) directly instead of create a C++ wrapper. Furthermore by plain P/Invoke you will drastically simplify the deploy ( no additional dll needed )

Upvotes: 2

Related Questions