How does an unmanaged c++ .dll know where the location of a managed c# .dll is?
Some context:
I have a c++ .dll that imports a type library (.tlb) and inside one of the c++ functions, I instantiate a pointer to the functions inside the c# .dll. Then, using that pointer, I can call the c# functions in c++. I would like to know how c++ .dll know where the c# .dll is? Further, is there a better way to do this type of coding?
Does the .tlb need to be in the same directory as the c# .dll?
One way to accomplishing the above is to register the C# dll file with the Microsoft Windows Registry using the regasm command. This command EXE is included with distributions of Visual Studios. An example use of the command follows:
regasm NameofC#DLL.dll /tlb:NameofC#DLL.tlb
Once you have registered it in the registry you will need to install it to the global assembly cache (GAC) using the gacutil command. This is also included with distributions of Visual Studios. An example use of the command follows:
gacutil /i NameofC#DLL.dll
Once these steps are completed your C++ code will be able to find the C# dll assuming your DLL files are constructed similar to the following:
[C#]
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace MyNameSpace
{
/// <summary>
/// Interface for C++ DLL. This exposes the functions used inside the dll
/// Make sure the return types, function names, and argument types match the class
/// </summary>
[ComVisible(true)]
[Guid("CBA208F2-E43B-4958-97C7-C24EA5A213DE")]
public interface IMyClass
{
int Function1();
int Function2();
}
[ClassInterface(ClassInterfaceType.None)]
[Guid("579091E6-83A1-4aa5-89A7-F432AB2A57E3")]
[ComVisible(true)]
public class MyClass : IMyClass
{
public MyClass()
{
//Constructor
}
public int Function1()
{
//Do something in C#
return an integer;
}
public int Function2()
{
//Do something else in C#
return an integer;
}
}//End Class MyClass
}//End namespace MyNameSpace
Everywhere you see a GUID being used, that is a randomly generated global identifier used to identify your C# code. This number can be randomly generated using the GUID creation tool provided with Visual Studios under the "Tool menu" and the "Create GUID" option. Select Registry format and press "New GUID". Then just press copy and paste it where the GUID needs to be (Remove the brackets!)
[C++]
#include <windows.h>
#include "stdafx.h"
#include <cstdlib>
#pragma warning (disable: 4278)
#import <mscorlib.tlb> raw_interfaces_only
#include <stdio.h>
//This path needs to be valid at compile time. The file does not need to be there in runtime when using the DLL after compile.
#import "C:\\...\\NameofC#DLL.tlb" no_namespace named_guids
extern "C" _declspec(dllexport) int _Function1()
{
int result = 0;
IMyClass *CSharpInterface = NULL;
//Open interface to C#
CoInitialize(NULL);
HRESULT hr = CoCreateInstance(CLSID_MyClass, NULL, CLSCTX_INPROC_SERVER,
IID_IMyClass, reinterpret_cast<void**>(&CSharpInterface));
//Call Function1 C# method
result = CSharpInterface->Function1();
//Close interface
CoUninitialize();
//Return result
return result;
}
The required TLB file at compile time can be generated using the tlbexp command also included with visual studios.An example use of the command follows:
tlbexp NameofC#DLL.dll
If you do not specify a path it will default to the following path:
C:\Program Files\Microsoft Visual Studio 9.0\VC
There a several places you can mess this up and the C# DLL call will fail.
Regards,
SeaMossDesign
Maybe I'm missing something, but you can create a custom CLR host and invoke a method from C# without pointer. Check ICLRRuntimeHost::ExecuteInDefaultAppDomain out.
Related
I need to import a dll made in c# from c++
All the examples I found import a single function from a dll, but as far as I know, you cannot export a single function from c# without exporting the whole class (I'm a bit of a c# newbie though)
I am using node gyp to compile it (I'm building a node module for my web app using v8)
Here is my c# code:
using System;
using System.IO;
using System.Runtime.InteropServices;
[ComVisible(true)]
public class Hello
{
public static void Main()
{
Console.WriteLine("Hello World!");
string createText = "Hello World" + Environment.NewLine;
File.WriteAllText(".\\asd.txt", createText);
}
}
And this is my c++ header file:
#ifndef ASDLIB_H
#define ASDLIB_H
#define ASD_IMPORT __declspec(dllimport)
#define STDCALL __stdcall
class ASD_IMPORT Hello{
public:
STDCALL static void ASD_IMPORT Main();
};
#endif // ASDLIB_H
I normally do this kind of stuff by creating a static C++ CLR Wrapper Lib.
These are the steps I'm normally using (although I don't use it very often):
Here minimal example with using Visual Studio:
1. Create managed C# .NET library Project
Let name it HelloLibManaged
with one file Hello.cs and following content:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HelloLibManaged
{
public class Hello
{
public void Print()
{
System.Console.WriteLine("Hello from Managed Lib");
}
}
}
Build this lib with x86 or x64 , just dont Any CPU
2. Create a new C++ CLR static lib project within same solution.
Let's name it HelloLibCpp
Add a reference to HelloLibManaged project via Project->Add Reference
Remove automatic created existing .h/.cpp files from Project, and create these 2 files:
HelloUnmanaged.h
#pragma once
namespace hello_managed {
class Hello
{
public:
void Print();
};
}
and
HelloUnmanaged.cpp:
#include "HelloUnmanaged.h"
namespace hello_managed
{
void Hello::Print()
{
HelloLibManaged::Hello^ hello = gcnew HelloLibManaged::Hello();
hello->Print();
}
}
Und Project Properties -> General specify static lib.
In the Build settings specify x86 / x64 - use the same build type as building Managed lib from Step 1.
Now you can build the dll and use it in your other unmanaged C++ projects.
For more advanced stuff, like return types and methods with parameters you have to do Type-Marshalling between managed/unmanaged code. There are many resources online with more information about Type-Conversion between managed/unmanaged code. Keyword: Marshaling.
I am working on WP8 project that includes class library project as C# source code and Windows Runtime Component as C++ source code. Does anyone know whether or not it is possible to create such C# class library which would reference Windows Runtime Component? The ultimate result should be .NET assembly and .WIMND/.DLL runtime component that can be used for application. Currently I cannot build class library because it doesn't see Windows Runtime Component, even though I added it to the project.
More specific. I have, say, MyNs.MyClass.MyMethod() which is defined in C++ runtime component and used from C# class library. Currently I cannot compile C# due to missing method although I have windows runtime component project attached to the same solution.
Although I am butting in because this is not my area, I tried Googling for "c# call windows runtime component". There seem to be many hits/examples, e.g. the first one is https://msdn.microsoft.com/en-us/library/hh755833.aspx.
Does that not help you?
I solved this by adding reference to Windows runtime component manually into the C# class library .csproj file as follows
...
<ItemGroup>
<Reference Include="WindowsRuntimeComponent.winmd" />
</ItemGroup>
...
I managed to make a C++ WRL project and use a class in that project from a C# project by adding a reference in the normal way. The Wrl project (not C++/CX, which also works) was made using some WRL template that I found somewhere on the web. The wrl project required me to make a .idl to define the interface, and produced its .dll and .winmd. Here is some code for those who are battling with this type of thing:
The Wrl class:
#include "pch.h"
#include "WrlTestClass2_h.h"
#include <wrl.h>
using namespace Microsoft::WRL;
using namespace Windows::Foundation;
namespace ABI
{
namespace WrlTestClass2
{
class WinRTClass: public RuntimeClass<IWinRTClass>
{
InspectableClass(RuntimeClass_WrlTestClass2_WinRTClass, BaseTrust)
public:
WinRTClass()
{
}
// http://msdn.microsoft.com/en-us/library/jj155856.aspx
// Walkthrough: Creating a Basic Windows Runtime Component Using WRL
HRESULT __stdcall Add(_In_ int a, _In_ int b, _Out_ int* value)
{
if (value == nullptr)
{
return E_POINTER;
}
*value = a + b;
return S_OK;
}
};
ActivatableClass(WinRTClass);
}
}
The C# code that uses this class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
namespace CSharpClientToWrl
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
WrlTestClass2.WinRTClass _winRtTestClass = new WrlTestClass2.WinRTClass();
int _answer = _winRtTestClass.Add(4, 6);
Assert.AreEqual(_answer, 10);
}
}
}
The .idl file of the wrl project:
import "inspectable.idl"; import "Windows.Foundation.idl";
#define COMPONENT_VERSION 1.0
namespace WrlTestClass2 {
interface IWinRTClass;
runtimeclass WinRTClass;
[uuid(0be9429f-2c7a-40e8-bb0a-85bcb1749367), version(COMPONENT_VERSION)]
interface IWinRTClass : IInspectable
{ // http://msdn.microsoft.com/en-us/library/jj155856.aspx // Walkthrough: Creating a Basic Windows Runtime Component Using WRL HRESULT Add([in] int a, [in] int b, [out, retval] int* value);
}
[version(COMPONENT_VERSION), activatable(COMPONENT_VERSION)]
runtimeclass WinRTClass
{
[default] interface IWinRTClass;
} }
Function calls from Java to C# through JNI-C++/CLI are failing when the C# COM is not registered using regasm with the codebase option. I've built a sample following the instructions in P2: Calling C# from Java with some changes.
Numero uno: C#
Change the C# dll into a COM by creating an interface, IRunner, and making the library assembly COM-visible.
namespace RunnerCOM
{
public interface IRunner
{
String ping();
}
public class Runner:IRunner
{
static void Main(string[] args)
{
}
public Runner() { }
public String ping()
{
return "Alive (C#)";
}
}
}
Numero due: Java
No changes made to the Java section.
Numero tre: C++
This part was changed to create a new instance of the RunnerCOM.Runner class and use that result. Here is a good tutorial on how to call managed code from unmanaged code: http://support.microsoft.com/kb/828736
#include "stdafx.h"
#include "Runner.h"
#pragma once
#using <mscorlib.dll>
#import "RunnerCOM.tlb"
JNIEXPORT jstring JNICALL Java_Runner_ping(JNIEnv *env, jobject obj){
RunnerCOM::IRunnerPtr t = RunnerCOM::IRunnerPtr("RunnerCOM.Runner");
BSTR ping = t->ping();
_bstr_t temp(ping, true);
char cap[128];
for(unsigned int i=0;i<temp.length();i++){
cap[i] = (char)ping[i];
}
return env->NewStringUTF(cap);
}
Now to my questions,
The code above fails with a _com_error exception, Class not registered (0x80040154) unless the codebase option is enabled during regsitration of RunnerCOM.dll, with regasm.exe. Why is this? If the code is not ran from JNI, I tested it as an exe, it works fine. The RunnerCOM.dll is simply found in the working directory.
Type casting _bstr_t temp to char* fails. For example, char *out = (char*) temp; Similar to the issue above, it works fine when it's built and executed as an exe but crashes the JVM when it's a JNI call.
By the way this is what I used to run it as an executable:
int main(){
RunnerCOM::IRunnerPtr t = RunnerCOM::IRunnerPtr("RunnerCOM.Runner");
BSTR ping = t->ping();
_bstr_t temp(ping, false);
printf(temp);
return 0;
}
Codebase creates a Codebase entry in the registry. The Codebase entry specifies the file path for an assembly that is not installed in the global assembly cache, so when you specify the codebase, the system will find the DLL based on the path. If not, it will try to locate the dll in the GAC and current working directory. In JNI, I think the current working directory is not the folder where the DLL is. You can use process explorer to find what is the current working directory, also, you can use process monitor to find out which directories the exe is looking into to find the dll.
The code converting _bstr_t to char*, the char* string cap is not ended with '\0', I think this might cause problem in JNI. Uses the _bstr_t operator (char *), you can obtain a null terminated string from the _bstr_t object. Please check the msdn example for details.
You mentioned C++/CLI, C++/Cli and COM warpper are two different ways to interop with C# code. If you're using C++/CLI as a bridge, you doesn't need to register C# DLL as COM, please see this: Calling .Net Dlls from Java code without using regasm.
If you're using COM, you should call CoInitialize() to init COM first in your code.
I tried to call the function from .dll file using java native interface ,its successfully working, But I don't know how to call function from .dll using C# ,please advice me on this.
Look at DLLImport attribute in MSDN
http://msdn.microsoft.com/en-us/library/aa664436(v=vs.71).aspx
using System;
using System.Runtime.InteropServices;
class Example
{
[DllImport("your_dll_here.dll")]
static extern int SomeFuncion1(int parm);
static void Main()
{
int result = SomeFunction1(10);
}
}
If it's a native DLL, you need to add a DLLImport statement, importing the function you want.
The documentation is here.
The attribute looks like this, typically:
[DllImport("YourDllNameHere.dll")]
public static extern int YourFunction(int input);
This will import a function called YourFunction (which takes an int input, and returns an int) from YourDllNameHere.dll.
Let's say your DLL name is MyLibrary and MyFunction is the function contain in your DLL .
First right click on your Reference , browse and add your DLL .
Declare your DLL as a namespace using MyLibrary;
And you can call MyFunction !
Or
Another way ,
you can use this msdn reference !
Add that dll into your project as a referenced dll into reference folder(right click on references ,add reference then "Browse" to you DLL).then it should be available for to use as you want and just use that dll as follows in the code level.
using System;
using YourDllName;
class ExampleClass
{
//you can use your dll functions
}
I like the link provided by Baldrick for DllImport attribute.
This is what I recommend.
Download Dependency Walker (small application exe, no need to install).
Open your DLL in the Dependecy Walker to view the exposed entry points of DLL.
Declare external call to native function in C# like this.
C#:
[DllImport("Your_DLL.DLL", EntryPoint="Function_Entry_Point",CallingConvention=CallingConvention.StdCall)]
static extern IntPtr Function1();
Note:
If entry point is not specified the function name is considered as the entry point.
When you run the application make sure the native DLL is in the
same folder.
i'm converting C++ to C++/CLI and would like to expose some managed classes as COM objects. In C# it was easy and setting [ComVisible] & inheriting from interface (also ComVisible) did the job.
However C++ project build as C++/CLI does not export DllRegisterServer.
Here is sample project (started from CLR Console Application project in VS 2008).
#include "stdafx.h"
using namespace System;
using namespace System::Runtime::InteropServices;
[ComVisible(true)]
[Guid("E3CF8A18-E4A0-4bc3-894E-E9C8648DC1F0")]
[InterfaceType(ComInterfaceType::InterfaceIsDual)]
public interface class ITestInterface
{
void TestMethod();
};
[ComVisible(true)]
[Guid("1514adf6-7cb0-4561-9fbb-b75c0467149b")]
public ref class CliComClass : ITestInterface
{
public:
virtual void TestMethod()
{
}
};
int main(array<System::String ^> ^args)
{
Console::WriteLine(L"Hello World");
return 0;
}
When I run regsvr32 on output .exe I got error saying DllRegisterServer was not found. I've tried google for some help but with no success.
You need to use TlbExp instead, TlbExp is the tool use to export managed classes to COM, it will read the assembly find the ComVisible type and register them.