I am trying to call my C++ library from my C# application (via C++/CLI). I followed the example from this question (for my specific application). The setup of my application is:
Unfortunately, when I actually go to access the CLR wrapper object in my C# application, I receive the following error:
The type or namespace name 'YourClass' could not be found (are you missing a using directive or an assembly reference?)
Do I have the project setup incorrectly, or is there something else I should be looking into? (Unfortunately, I cannot post the code for proprietary reasons, but it is a very simple bit of code and easily follows the above example.)
Update:
So I did exactly what Chris said to do (see answer below), but I am still receiving a message from my C# application that "The type or namespace name 'MyProgram' could not be found (are you missing a using directive or an assembly reference?). Here is a (mock-up) of my code.
MyWrapper.h
#pragma once
#include "myorigapp.h"
using namespace System;
namespace MyProgram
{
public ref class MyWrapper
{
private:
myorigapp* NativePtr;
public:
MyWrapper()
{
NativePtr = new myorigapp();
}
~MyWrapper()
{
delete NativePtr;
NativePtr = NULL;
}
void dostuff()
{
NativePtr->dostuff();
}
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MyProgram;
namespace Testing
{
class Program
{
static void Main(string[] args)
{
MyWrapper p = new MyWrapper();
p.dostuff();
}
}
}
Project3 references Project2 which references Project1. Everything builds without errors (except the error I described above in the C# code on the using MyProgram
line).
Just including the header from a pure C++ application isn't good enough. You need to wrap your unmanaged objects with managed ones in Project2 (i.e. public ref class YourClassDotNet
)
#include "YourHeader.h"
namespace MyManagedWrapper
{
public ref class YourClassDotNet
{
private:
YourClass* ptr;
public:
YourClassDotNet()
{
ptr = new YourClass();
}
~YourClassDotNet()
{
this->!YourClassDotNet();
}
!YourClassDotNet()
{
delete ptr;
ptr = NULL;
}
void SomeMethod()
{
ptr->SomeMethod();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With