I'm trying to learn how to call unmanaged code from C# but I'm finding it difficult. So far I have managed to set up a simple scenario using basic types that work:
Test.h:
#pragma once
class TestWCM
{
public:
int Hello();
private:
};
Test.cpp:
#include "Test.h"
int TestWCM::Hello()
{
return 42;
}
I then created a Visual C++ Class Library project:
WCM_Wrapper_Lib.h:
#include "C:\Test.h"
#include "C:\Test.cpp"
using namespace System;
namespace WCM_Wrapper_Lib {
public ref class TestWrapper
{
public:
TestWrapper();
~TestWrapper();
int Hello();
private:
TestWCM* test;
};
}
WCM_Wrapper_Lib.cpp:
#include "stdafx.h"
#include "WCM_Wrapper_Lib.h"
WCM_Wrapper_Lib::TestWrapper::TestWrapper()
{
test = new TestWCM();
}
WCM_Wrapper_Lib::TestWrapper::~TestWrapper()
{
delete test;
}
int
WCM_Wrapper_Lib::TestWrapper::Hello()
{
return test->Hello();
}
Finally I Created a Windows Forms Application where I added the .dll as a reference.
Form1.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WCM_Wrapper_Lib;
namespace WCM2_GUI
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
TestWrapper testWrapper = new TestWrapper();
MessageBox.Show(testWrapper.Hello().ToString());
}
}
}
Now my question is, how would I have to modify this code if instead of an int, I would like Hello() to return a simple struct instead:
struct TestStruct
{
int first;
float second;
};
public value structkeywords so the C# code can use it. Do note that your class wrapper has a bug, it should implement a finalizer (!TestWrapper) so you don't leak memory when the client code does not call Dispose().