Adrien Brunelat
Adrien Brunelat

Reputation: 4642

Wrap a C struct for access in WPF application

for a project of mine, I'd like to wrap a C struct in order to use it in C# code. My C++ algorithm returns a struct object and I'd like to see contained informations from C#/WPF code.

When I try "my way", I get an error message while compiling : "'Wrapper.WrapperAlgo.createMediumMap()' is inaccessible due to its protection level"

my C# piece of code:

public partial class MainWindow : Window
{    
    unsafe public MainWindow()
    {
        WrapperAlgo algo = new WrapperAlgo();
        square** map = (square**)algo.createMediumMap();
    }
}

My wrapper

#ifndef __WRAPPER__
#define __WRAPPER__

#include "../CivilizationAlgo/mapalgo.h"
#pragma comment(lib, "../Debug/CivilizationAlgo.lib")

using namespace System;

namespace Wrapper {
    public ref class WrapperAlgo {
        private:
            Algo* algo;
    public:
        WrapperAlgo(){ algo = Algo_new(); }
        ~WrapperAlgo(){ Algo_delete(algo); }
        square** createSmallMap() { return algo->createSmallMap(); }
        square** createMediumMap() { return algo->createMediumMap(); }
        int computeFoo() { return algo->computeFoo(); }
    };
}
#endif

My C++ algo.h with the struct I'd like to use in C#

#ifdef WANTDLLEXP
#define DLL _declspec(dllexport)
#define EXTERNC extern "C"
#else
#define DLL
#define EXTERNC
#endif

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <vector>

using namespace std;

struct square {
    // 0: Mountain, 1: Plain, 2: Desert
    int type;
    // 0: No additionnal ressource, 1: Additionnal Iron, 2: Additionnal Food
    int bonus;
    // 0: free, 1: checked, 2: frozen
    int state;
};

class DLL Algo {
    public:
        Algo() {}
        ~Algo() {}
        square** createSmallMap();
        square** createMediumMap();
        int computeFoo();
};

Do you have any idea where i'm wrong ?

Upvotes: 2

Views: 630

Answers (1)

SOReader
SOReader

Reputation: 6027

If I understand you well you are looking for a way to use non-managed library (like cpp/c library) in your C# code. If yes, then you should read about marshaling, for ex. here, here, or here.

Basics about including unmanaged code in C# app can be found on MSDN, or MSDN Magazine.

Hope it helps.

Upvotes: 2

Related Questions