VC++ .net: Functionality from managed DLL is not exported - c#

I am very new to the .NET platform (coming from the JVM and having some limited C/C++ experience) and trying my first managed C++ class library. This is to serve as a bridge to a third-party DLL I got and I have to interface. I tried it with BridJ and Java but had no success so far, so I am now trying to write the program which uses the third-party DLL in C#.
The third-party DLL is unmanaged C++.
My ManagedBridge.h so far looks similar to this:
#pragma once
#include "thirdparty.h"
using namespace System;
namespace ManagedBridge {
class __declspec(dllexport) BridgedThirdPartyThing {
private:
THIRDPARTYNS::ThirdPartyThing* _delegate;
public:
BridgedThirdPartyThing();
~BridgedThirdPartyThing();
void foo();
// more methods
};
}
My ManagedBridge.cpp so far looks like this:
#include "stdafx.h"
#include "ManagedBridge.h"
namespace ManagedBridge {
BridgedThirdPartyThing::BridgedThirdPartyThing() {
_delegate = new THIRDPARTYNS::ThirdPartyThing();
}
BridgedThirdPartyThing::~BridgedThirdPartyThing() {
delete _delegate;
}
void BridgedThirdPartyThing::foo() {
_delegate -> foo();
}
// similar for the other methods
}
}
Now, when I build this, I get no errors, and a ManagedBridge.dll is created.
I then created a C# Console application to test my DLL, added it as a reference, but I cannot access the class I exported with __declspec(dllexport). Only the namespace is shown in the object browser.
What am I missing?

It's
public ref class BridgedThirdPartyThing
for C++/CLI. You don't use __declspec(dllexport). Note that the class needs to be public to be visible to comsuming assemblies.

Related

Using C# code in C++ (COM) Dll import not working quite right

As the title implies, I am having difficulty calling C# code from C++. A bit of context: there is an API call in C# (that does not exist in the C++ version of the API) and I need to integrate it into a much larger C++ project.
I have been reading over this SO post, and made the most headway with the COM method.
My C# dll compiles*. After copying the resulting dll and tlb files into the appropriate C++ project directory, I open an admin cmd prompt in the same C++ project directory and run:
regasm MyFirstDll.dll /codebase /tlb
(*I compile it as a Class Library, Assembly name: MyFirstDll, Default namespace: MyMethods, Assembly Information... -> Make assembly Com-Visible is checked, Build->Register for COM interop is also checked.)
Using the Object Browser, I am able to see the class I defined, as well as a method with the appropriate args and signature.
Screenshot of it showing up in Object Browser
The issue I am experiencing is with the method call (and not the class). Even though the method is visible in the Object Browser, in my code it is not recognized as a method of the object.
class "ATL::_NoAddRefReleaseOnCComPtr" has no member "Add"
Here is my code:
MyFirstDll C# Project:
using System;
using System.Runtime.InteropServices;
//
namespace MyMethods
{
// Interface declaration.
[Guid("8a0f4457-b08f-4124-bc49-18fe11cb108e")]
[ComVisible(true)]
[InterfaceType(ComInterfaceType.InterfaceIsDual)]
public interface Easy_Math
{
[DispId(1)]
long Add(long i, long j);
};
}
namespace MyMethods
{
[Guid("0cb5e240-0df8-4a13-87dc-50823a395ec1")]
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[ProgId("MyMethods.AddClass")]
public class AddClass: Easy_Math
{
public AddClass() { }
[ComVisible(true)]
public long Add(long i, long j)
{
return (i + j);
}
}
}
NateMath.h:
#include <atlcomcli.h>
#import "MyFirstDll.tlb"
class NateMath
{
public:
NateMath(void);
~NateMath(void);
long Add(long a, long b);
private:
CComPtr<MyFirstDll::AddClass> adder;
};
NateMath.cpp:
#include "stdafx.h"
#include <atlcomcli.h>
#import "MyFirstDll.tlb"
#include "NateMath.h"
NateMath::NateMath(void)
{
CoInitialize(NULL);
adder.CoCreateInstance(__uuidof(MyFirstDll::AddClass));
}
NateMath::~NateMath(void)
{
CoUninitialize();
}
long NateMath::Add(long a, long b) {
return adder->Add(a,b);
}
The issue being that in "return adder->Add(a,b)" (NateMath.cpp) Add(a,b) shows up red with class "ATL::_NoAddRefReleaseOnCComPtr" has no member "Add"
This is because you are trying to use your class name in CComPtr instead of the interface. With COM, all methods are defined on an interface, not on the class that implements an interfaces.
You can CoCreateInstance(__uuidof(YourClass)) because the intent is to create an instance of YourClass (which is identified by the GUID expressed by __uuidof(YourClass)). However, YourClass in the C++ is a dummy struct that's only present so that you can read the uuid -- the definition of YourClass in the C++ generated from the #import is empty and will always be empty.
To fix this, use CComPtr<YourInterface>. This tells the C++ that you want to communicate with the referenced object via that interface. Here's a rule to remember: The type argument to CComPtr and CComQIPtr must always be a COM interface. That COM interface can either be an explicitly-defined interface, or it can be the "class interface" which was automatically produced by .NET.
Speaking of class interfaces: If you had used ClassInterfaceType.AutoDual instead of None, you could have used a CComPtr<_YourClass> (note the leading underscore -- _YourClass is the class interface, whereas YourClass would be the class. I would recommend doing it the way you already have, however.

Calling native Win32 code from .NET (C++/CLI and C#)

I'm developing an app for C#, and I want to use DirectX (mostly Direct2D) for the graphical component of it. So I'm trying use use C++/CLI as an intermediary layer between the native C++ code and the managed code of C#. So far a have 3 projects in my solution: A C# project (which I won't really discuss since it's not giving me any problems yet), a C++ static library that includes Windows.h, and a dynamic C++/CLI library that's intended to marshal information between the other two projects. Here is my code so far:
In the native C++ project, I have a class named RenderWindowImpl that so for only contains 2 methods:
//RenderWindowImpl.h
#pragma once
#include <Windows.h>
class RenderWindowImpl final
{
public:
RenderWindowImpl() = default;
~RenderWindowImpl() = default;
int test();
private:
static void InitializeWin32Class();
};
// RenderWindowImpl.cpp
#include "RenderWindowImpl.h"
int RenderWindowImpl::test()
{
return 5;
}
void RenderWindowImpl::InitializeWin32Class()
{
WNDCLASSEXW wc = { 0 };
wc.cbSize = sizeof(WNDCLASSEXW);
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = nullptr;
wc.hInstance = GetModuleHandleW(0);
wc.hCursor = LoadCursorW(nullptr, IDC_ARROW);
//wc.lpszClassName = L"wz.1RenderWindowImpl";
//// TODO: error check
//RegisterClassExW(&wc);
}
And in my C++/CLI project, I have a class named RenderWindow that acts as a wrapper around RenderWindowImpl:
// wzRenderWindow.h
#pragma once
//#pragma managed(push, off)
#include "RenderWindowImpl.h"
//#pragma managed(pop)
using namespace System;
namespace wzRenderWindow {
public ref class RenderWindow sealed
{
public:
RenderWindow();
~RenderWindow();
int test();
private:
RenderWindowImpl* impl;
};
}
// wzRenderWindow.h.
#include "stdafx.h"
#include "wzRenderWindow.h"
wzRenderWindow::RenderWindow::RenderWindow()
{
// Initialize unmanaged resource
impl = new RenderWindowImpl();
try
{
// Any factory logic can go here
}
catch (...)
{
// Catch any exception and avoid memory leak
delete impl;
throw;
}
}
wzRenderWindow::RenderWindow::~RenderWindow()
{
// Delete unmanaged resource
delete impl;
}
int wzRenderWindow::RenderWindow::test()
{
return impl->test();
}
When I compile my project, I get the following warnings and errors:
Error LNK1120 1 unresolved externals wzRenderWindow d:\documents\visual studio 2015\Projects\WizEngCS\Debug\wzRenderWindow.dll 1
Warning LNK4075 ignoring '/EDITANDCONTINUE' due to '/OPT:LBR' specification wzRenderWindow d:\documents\visual studio 2015\Projects\WizEngCS\wzRenderWindow\wzRenderWindowImpl.lib(RenderWindowImpl.obj) 1
Error LNK2019 unresolved external symbol __imp__LoadCursorW#8 referenced in function "private: static void __cdecl RenderWindowImpl::InitializeWin32Class(void)" (?InitializeWin32Class#RenderWindowImpl##CAXXZ) wzRenderWindow d:\documents\visual studio 2015\Projects\WizEngCS\wzRenderWindow\wzRenderWindowImpl.lib(RenderWindowImpl.obj) 1
It seems to be the call to LoadCursorW that C++/CLI doesn't like, as the code compiles fine if I comment out that line. With the Win32 function calls removed, I was able to successfully call RenderWindow::test() from a C# application, outputting the expected result of 5.
I'm a bit of a loss because my understanding of C++/CLI is that it's very good at wrapping native C++ classes for consumption by managed .NET applications. I would really like to understand why my code is not compiling.
As a related follow-up question, am I barking up the wrong tree here? What's the conventional way to access DirectX methods (or similar COM-based C/C++ libraries) from .NET? I'd like to avoid using 3rd-party wrapper libraries like SharpDX.
I fixed the problem by putting #pragma comment(lib, "User32.lib") at the top of my RenderWindowImpl.cpp. Thanks to #andlabs for the fix. I'm not sure why this fixed the problem (I've never needed to explicitly link to user32.lib in any of my previous projects).

Dynamically load a C# .NET assembly in a C++Builder application

I have a C++ Windows application developped with RAD Studio (C++Builder) XE4. It has some plugins, which are DLLs (always written with RAD Studio) that are dynamically loaded with this technique.
Now in one of this plugins I need reflection capabilities. While it seems I cannot achieve them with C++ (reflection is needed on a third-party COM DLL that I cannot modify) I decided to rewrite this plugin in C# (which has powerful reflection capabilities), thus creating a .NET assembly.
I know I should expose the assembly via COM, but I can't (we don't want to change the way the main application loads all DLLs).
My aim is to dynamically load the .NET assembly and invoke its functions (for instance here we call SetParam function) with something like the following, like I do with the other plugins.
//load DLL
HINSTANCE handleDll = LoadLibraryW("C:/Path/to/the/assembly.dll");
//get reference to the function
void* ptr = GetProcAddress(handleDll, "_SetParam");
ptr_SetParam ptrFunc = reinterpret_cast<ptr_SetParam>(ptr);
//invoke function
int result = (*ptrFunc)(String("mykey").c_str(), String("myvalue").c_str());
where ptr_SetParam is defined as
typedef int(*ptr_SetParam)(const wchar_t*, const wchar_t*);
Is there a way?
Thanks to #HansPassant's comment I found a way.
I created following Visual Studio projects.
MyDllCore .NET assembly project, written in C# or any other .NET language. Here I have my managed class like the following, where the real logic of the assembly is implemented.
using System;
using System.Collections.Generic;
//more usings...
namespace MyNamespace
{
public class HostDllB1
{
private Dictionary<string, string> Parameters = new Dictionary<string, string>();
public HostDllB1()
{
}
public int SetParam(string name, string value)
{
Parameters[name] = value;
return 1;
}
}
}
MyDllBridge DLL project, written in C++/CLI, with /clr compiler option. It is just a "bridge" project, it has a dependancy on MyDllCore project and has just one .cpp o .h file like the following, where I map the methods from the program that loads the DLL to the methods in the .NET assembly.
using namespace std;
using namespace System;
using namespace MyNamespace;
//more namespaces...
#pragma once
#define __dll__
#include <string.h>
#include <wchar.h>
#include "vcclr.h"
//more includes...
//References to the managed objects (mainly written in C#)
ref class ManagedGlobals
{
public:
static MyManagedClass^ m = gcnew MyManagedClass;
};
int SetParam(const wchar_t* name, const wchar_t* value)
{
return ManagedGlobals::m->SetParam(gcnew String(name), gcnew String(value));
}
Finally I have a C++Builder program that loads MyDllBridge.dll and uses its methods calling them like in the following.
//load DLL
HINSTANCE handleDll = LoadLibraryW("C:/Path/to/the/MyDllBridge.dll");
//get reference to the function
void* ptr = GetProcAddress(handleDll, "SetParam");
ptr_SetParam ptrFunc = reinterpret_cast<ptr_SetParam>(ptr);
//invoke function
int result = (*ptrFunc)(String("mykey").c_str(), String("myvalue").c_str());

C++ written dll and C# call

After a long reading time I didn't get the dll working...
I tried so much different ways but no way worked..
I did the following things: (IDE: VS2013Ultimate)
I added a clean c++ project. There I added 1 header file [header.h]:
#pragma once
class myClass{
public:
myClass(double varx, double vary);
double sumxy();
private:
double x;
double y;
};
I added a body.cpp file:
#pragma once
#include "header.h"
myClass::myClass(double varx, double vary){
x = varx;
y = vary;
}
double myClass::sumxy(){
return x + y;
}
That's all the code I would need. I only want a working example code.
I added one class [main.cpp]:
#include "header.h"
#include "body.cpp"
extern "C" __declspec(dllexport) double sumxy(double var_x, double var_y){
myClass MC(var_x, var_y);
return MC.sumxy();
}
After this I compiled this dll and I got it without any compile errors. `I copied it to the debug folder of the c# Console Application
C# Console Application:
using System.Runtime.InteropServices;
//all using directories
namespace Klassen_Tester {
class Program {
[DllImport("CppClassDll.dll")]
public static extern double sumxy(double var_x, double var_y);
static void Main(string[] args) {
Console.WriteLine(sumxy(3, 5).ToString());
Console.ReadLine();
}
}
}
Please help me. Don't know what to do.. And sorry for my bad english.
Edit: There is an error: System.DllNotFoundException in Klassen_Tester.exe. DLL "CppClassDll.dll" could not be found. HRESULT: 0x8007007E) could not be load.
You might consider using an interop between C++ and C# so you don't have to mess with pinvoke. I'm not saying pinvoke is bad but interops are nice.
You are going to want to write a CLR wrapper to act as an intermediary between the managed and unmanaged code. It looks like you have the C# and C++ mostly written so I'll describe the CLR portion.
Create a CLR project in Visual Studio
Add your native C++ project as a reference
Write your wrapper
Add reference to CLR project from C# project
Call CLR wrapper
Create a class with your C++ signatures likes this:
namespace YourWrapper
{
public ref class WrappedFunction
{
public:
// Adjust according to your c++ class and function
double sumxy(double a, double b) {
return myClass::sumxy(a, b);
}
};
}
For a full example, see my project https://github.com/corytodd/interop-example:

Export c++ functions inside a C# Application

Greetings,
I am sorry for bothering, I'll show the question:
I am trying to export some functions written in c++ in a DLL in order to import them in a C# Application running on Visual Studio.
I make the export as reported in the following code,
tobeexported.h:
namespace SOMENAMESPACE
{
class __declspec(dllexport) SOMECLASS
{
public:
SOMETYPE func(param A,char b[tot]);
};
}
tobeexported.cpp:
#include "stdafx.h"
#include "tobeexported.h"
...
using namespace SOMENAMESPACE;
SOMETYPE SOMECLASS:: func(param A,char b[tot])
{
...some stuff inside...
}
The dll is righly created and the code is already CLR-managed(looked with a disassembling software(reflector)) and contains the exported functions
then I "Add the Reference" in my c# application and the dll is found, but when
I open it with the object browser it is completely empty, neither class, nor object has been exported and ready to be used
can you help me please?
thanks
best regards
What about using managed C++ to compile your DLL? Then you just have to add a ref to the class like this:
namespace SOMENAMESPACE
{
public ref class SOMECLASS
{
public:
SOMETYPE func(param A,char b[tot]);
};
}
After successful compilation and referencing in the other project, the class should be visible. Exporting native C++ is not really portable, each compiler produces different results and is tedious to bind from within C#...
EDIT: added public access modifier to ref class...

Categories