So what I have is a C++ API contained within a *.dll and I want to use a C# application to call methods within the API.
So far I have created a C++ / CLR project that includes the native C++ API and managed to create a "bridge" class that looks a bit like the following:
// ManagedBridge.h
#include <CoreAPI.h>
using namespace __CORE_API;
namespace ManagedAPIWrapper
{
public ref class Bridge
{
public:
int bridge_test(void);
int bridge_test2(api_struct* temp);
}
}
.
// ManagedBridge.cpp
#include <ManagedBridge.h>
int Bridge::bridge_test(void)
{
return test();
}
int Bridge::bridge_test2(api_struct* temp)
{
return test2(temp);
}
I also have a C# application that has a reference to the C++/CLR "Bridge.dll" and then uses the methods contained within. I have a number of problems with this:
I can't figure out how to call bridge_test2 within the C# program, as it has no knowledge of what a api_struct actually is. I know that I need to marshal the object somewhere, but do I do it in the C# program or the C++/CLR bridge?
This seems like a very long-winded way of exposing all of the methods in the API, is there not an easier way that I'm missing out? (That doesn't use P/Invoke!)
EDIT: Ok, so I've got the basics working now thanks to responses below, however my struct (call it "api_struct2" for this example) has both a native enum and union in the C++ native code, like the following:
typedef struct
{
enum_type1 eEnumExample;
union
{
long lData;
int iData;
unsigned char ucArray[128];
char *cString;
void *pvoid;
} uData;
} api_struct2;
I think I have figured out how to get the enum working; I've re-declared it in managed code and am performing a "native_enum test = static_cast(eEnumExample)" to switch the managed version to native.
However the union has got me stumped, I'm not really sure how to attack it.. Ideas anyone?
Yes, you are passing an unmanaged structure by reference. That's a problem for a C# program, pointers are quite incompatible with garbage collection. Not counting the fact that it probably doesn't have the declaration for the structure either.
You can solve it by declaring a managed version of the structure:
public value struct managed_api_struct {
// Members...
};
Now you can declare the method as
int bridge_test2(managed_api_struct temp); // pass by value
or
int bridge_test2(managed_api_struct% temp); // pass by reference
Pick the latter if the structure has more than 4 fields (~16 bytes). The method needs to copy the structure members, one-by-one, into an unmanaged api_struct and call the unmanaged class method. This is unfortunately necessary because the memory layout of a managed structure is not predictable.
This is all pretty mechanical, you might get help from SWIG. Haven't used it myself, not sure if it is smart enough to deal with a passed structure.
A completely different approach is to make the wrapper class cleaner by giving it a constructor and/or properties that lets you build the content of an api_struct. Or you could declare a wrapper ref class for the structure, much like you would in managed code.
as it has no knowledge of what a api_struct actually is
You need to define a managed version in a .NET assembly, that uses attributes (like StructLayoutAttribute) to ensure it marshals correctly.
This seems like a very long-winded [...]
The other approach is to create a COM wrapper (e.g. using ATL) around your API. This might be more effort, but at least you avoid the double coding of struct and function definitions needed for P/Invoke.
Correction: You have created a C++/CLI project: so just add correct '#pragma' to tell the compiler this is .NET code, and then the output is an assembly the C# project can just reference.
Yuo are trying to do this way more complicated that it really is. What you want is two different structs. One managed and one unmanaged. You expose the managed version externally (to your C# app). It will be all ".Net-ish" with no concepts of unions or so.
In your bridge you receive the managed version of the struct, manually create the unmanaged struct and write code to move your data, field by field over to the unmanaged struct. Then call your unmanaged code and finally move the data back to the managed struct.
The beautiful thing about C++/CLI is that the managed code also can work with unmanaged code and data (and include the unmanaged .h files).
Related
Background: As part of a larger assignment I need to make a C# library accessible to unmanaged C++ and C code. In an attempt to answer this question myself I have been learning C++/CLI the past few days/ weeks.
There seems to be a number of different ways to achieve using a C# dll from unmanaged C++ and C. Some of the answers in brief appear to be: using Interlope services, Using .com. and regasm, Using PInvoke (which appears to go from C# to C++ only), and using IJW in the C++/CLR (which appears to be Interlope services). I am thinking it would be best to set up a library that is perhaps a CLR wrapper that uses IJW to call my C# dll on the behalf of native C++ and C code.
Specifics: I need to pass values of string as well as int to a C# dll from c++ code, and return void.
Relevance: Many companies have many excuses to mix and match C++, C and C#. Performance: unmanaged code is usually faster, interfaces: Managed interfaces are generally easier to maintain, deploy, and are often easier on the eyes, Managers tell us too. Legacy code forces us too. It was there (Like the mountain that we climbed). While examples of how to call a C++ library from C# are abundant. Examples of how to call C# libraries from C++ code are difficult to find via Googling especially if you want to see updated 4.0+ code.
Software: C#, C++/CLR, C++, C, Visual Studio 2010, and .NET 4.0
Question details: OK multi-part question:
Is there an advantage to using com objects? Or the PInvoke? Or some other method? (I feel like the learning curve here will be just as steep, even though I do find more information on the topic in Google Land. IJW seems to promise what I want it to do. Should I give up on looking for an IJW solution and focus on this instead?) (Advantage/ disadvantage?)
Am I correct in imagining that there is a solution where I write a wrapper that that utilizes IJW in the C++/CLR? Where can I find more information on this topic, and don’t say I didn’t Google enough/ or look at MSDN without telling me where you saw it there. (I think I prefer this option, in the effort to write clear and simple code.)
A narrowing of question scope: I feel that my true issue and need is answering the smaller question that follows: How do I set up a C++/CLR library that an unmanaged C++ file can use within visual studio. I think that if I could simply instantiate a managed C++ class in unmanaged C++ code, then I might be able work out the rest (interfacing and wrapping etc.). I expect that my main folly is in trying to set up references/#includes etc. within Visual Studio, thought clearly I could have other misconceptions. Perhaps the answer to this whole thing could be just a link to a tutorial or instructions that help me with this.
Research: I have Googled and Binged over and over with some success. I have found many links that show you how to use an unmanaged library from C# code. And I will admit that there have been some links that show how to do it using com objects. Not many results were targeted at VS 2010.
References:
I have read over and over many posts. I have tried to work through the most relevant ones. Some seem tantalizingly close to the answer, but I just can’t seem to get them to work. I suspect that the thing that I am missing is tantalizingly small, such as misusing the keyword ref, or missing a #include or using statement, or a misuse of namespace, or not actually using the IJW feature properly, or missing a setting that VS needs to handle the compilation correctly, etc. So you wonder, why not include the code? Well I feel like I am not at a place where I understand and expect the code I have to work. I want to be in a place where I understand it, when I get there maybe then I'll need help fixing it. I'll randomly include two of the links but I am not permitted to show them all at my current Hitpoint level.
http://www.codeproject.com/Articles/35437/Moving-Data-between-Managed-Code-and-Unmanaged-Cod
This calls code from managed and unmanaged code in both directions going from C++ to Visual Basic and back via C++CLR, and of course I am interested in C#.: http://www.codeproject.com/Articles/9903/Calling-Managed-Code-from-Unmanaged-Code-and-vice
You can do this fairly easily.
Create an .h/.cpp combo
Enable /clr on the newly create .cpp file. (CPP -> Right click -> Properties)
Set the search path for "additional #using directories" to point towards your C# dll.
Native.h
void NativeWrapMethod();
Native.cpp
#using <mscorlib.dll>
#using <MyNet.dll>
using namespace MyNetNameSpace;
void NativeWrapMethod()
{
MyNetNameSpace::MyManagedClass::Method(); // static method
}
That's the basics of using a C# lib from C++\CLI with native code. (Just reference Native.h where needed, and call the function.)
Using C# code with managed C++\CLI code is roughly the same.
There is a lot of misinformation on this subject, so, hopefully this saves someone a lot of hassle. :)
I've done this in: VS2010 - VS2012 (It probably works in VS2008 too.)
UPDATE 2018
It seems like as if the solution does not work for Visual Studio 2017 and onwards. Unfortunately I am currently not working with Visual Studio and therefore cannot update this answer by myself. But kaylee posted an updated version of my answer, thank you!
UPDATE END
If you want to use COM, here's my solution for this problem:
C# library
First of all you need a COM compatible library.
You already got one? Perfect, you can skip this part.
You have access to the library? Make sure it's COM compatible by following the steps.
Make sure that you checked the "Register for COM interop" option in the properties of your project. Properties -> Build -> Scroll down -> Register for COM interop
The following screenshots shows where you find this option.
All the interfaces and classes that should be available need to have a GUID
namespace NamespaceOfYourProject
{
[Guid("add a GUID here")]
public interface IInterface
{
void Connect();
void Disconnect();
}
}
namespace NamespaceOfYourProject
{
[Guid("add a GUID here")]
public class ClassYouWantToUse: IInterface
{
private bool connected;
public void Connect()
{
//add code here
}
public void Disconnect()
{
//add code here
}
}
}
So that's pretty much what you have to do with your C# code. Let's continue with the C++ code.
C++
First of all we need to import the C# library.
After compiling your C# library there should be a .tlb file.
#import "path\to\the\file.tlb"
If you import this new created file to your file.cpp you can use your object as a local variable.
#import "path\to\the\file.tlb"
int _tmain(int argc, _TCHAR* argv[])
{
CoInitialize(NULL);
NamespaceOfYourProject::IInterfacePtr yourClass(__uuidof(NamespaceOfYourProject::ClassYouWantToUse));
yourClass->Connect();
CoUninitialize();
}
Using your class as an attribute.
You will noticed that the first step only works with a local variable. The following code shows how to use it as a attribute. Related to this question.
You will need the CComPtr, which is located in atlcomcli.h. Include this file in your header file.
CPlusPlusClass.h
#include <atlcomcli.h>
#import "path\to\the\file.tlb"
class CPlusPlusClass
{
public:
CPlusPlusClass(void);
~CPlusPlusClass(void);
void Connect(void);
private:
CComPtr<NamespaceOfYourProject::IInterface> yourClass;
}
CPlusPlusClass.cpp
CPlusPlusClass::CPlusPlusClass(void)
{
CoInitialize(NULL);
yourClass.CoCreateInstance(__uuidof(NamespaceOfYourProject::ClassYouWantToUse));
}
CPlusPlusClass::~CPlusPlusClass(void)
{
CoUninitialize();
}
void CPlusPlusClass::Connect(void)
{
yourClass->Connect();
}
That's it! Have fun with your C# classes in C++ with COM.
The answer from 0lli.rocks is unfortunately either outdated or incomplete. My co-worker helped me get this working, and to be frank one or two of the implementation details were not remotely obvious. This answer rectifies the gaps and should be directly copyable into Visual Studio 2017 for your own use.
Caveats: I haven't been able to get this working for C++/WinRT, just an FYI. All sorts of compile errors due to ambiguity of the IUnknown interface. I was also having problems getting this to work for just a library implementation instead of using it in the main of the app. I tried following the instructions from 0lli.rocks for that specifically, but was never able to get it compiling.
Step 01: Create your C# Library
Here's the one we'll be using for the demo:
using System;
using System.Runtime.InteropServices;
namespace MyCSharpClass
{
[ComVisible(true)] // Don't forget
[ClassInterface(ClassInterfaceType.AutoDual)] // these two lines
[Guid("485B98AF-53D4-4148-B2BD-CC3920BF0ADF")] // or this GUID
public class TheClass
{
public String GetTheThing(String arg) // Make sure this is public
{
return arg + "the thing";
}
}
}
Step 02 - Configure your C# library for COM-visibility
Sub-Step A - Register for COM interoperability
Sub-Step B - Make the assembly COM-visible
Step 3 - Build your Library for the .tlb file
You probably want to just do this as Release for AnyCPU unless you really need something more specific.
Step 4 - Copy the .tlb file into the source location for your C++ project
Step 5 - Import the .tlb file into your C++ project
#include "pch.h"
#include <iostream>
#include <Windows.h>
#import "MyCSharpClass.tlb" raw_interfaces_only
int wmain() {
return 0;
}
Step 6 - Don't panic when Intellisense fails
It will still build. You're going to see even more red-lined code once we implement the actual class into the C++ project.
Step 7 - Build your C++ project to generate the .tlh file
This file will go into your intermediate object build directory once you build the first time
Step 8 - Assess the .tlh file for implementation instructions
This is the .tlh file that is generated in the intermediate object folder. Don't edit it.
// Created by Microsoft (R) C/C++ Compiler Version 14.15.26730.0 (333f2c26).
//
// c:\users\user name\source\repos\consoleapplication6\consoleapplication6\debug\mycsharpclass.tlh
//
// C++ source equivalent of Win32 type library MyCSharpClass.tlb
// compiler-generated file created 10/26/18 at 14:04:14 - DO NOT EDIT!
//
// Cross-referenced type libraries:
//
// #import "C:\Windows\Microsoft.NET\Framework\v4.0.30319\mscorlib.tlb"
//
#pragma once
#pragma pack(push, 8)
#include <comdef.h>
namespace MyCSharpClass {
//
// Forward references and typedefs
//
struct __declspec(uuid("48b51671-5200-4e47-8914-eb1bd0200267"))
/* LIBID */ __MyCSharpClass;
struct /* coclass */ TheClass;
struct __declspec(uuid("1ed1036e-c4ae-31c1-8846-5ac75029cb93"))
/* dual interface */ _TheClass;
//
// Smart pointer typedef declarations
//
_COM_SMARTPTR_TYPEDEF(_TheClass, __uuidof(_TheClass));
//
// Type library items
//
struct __declspec(uuid("485b98af-53d4-4148-b2bd-cc3920bf0adf"))
TheClass;
// [ default ] interface _TheClass
// interface _Object
struct __declspec(uuid("1ed1036e-c4ae-31c1-8846-5ac75029cb93"))
_TheClass : IDispatch
{
//
// Raw methods provided by interface
//
virtual HRESULT __stdcall get_ToString (
/*[out,retval]*/ BSTR * pRetVal ) = 0;
virtual HRESULT __stdcall Equals (
/*[in]*/ VARIANT obj,
/*[out,retval]*/ VARIANT_BOOL * pRetVal ) = 0;
virtual HRESULT __stdcall GetHashCode (
/*[out,retval]*/ long * pRetVal ) = 0;
virtual HRESULT __stdcall GetType (
/*[out,retval]*/ struct _Type * * pRetVal ) = 0;
virtual HRESULT __stdcall GetTheThing (
/*[in]*/ BSTR arg,
/*[out,retval]*/ BSTR * pRetVal ) = 0;
};
} // namespace MyCSharpClass
#pragma pack(pop)
In that file, we see these lines for the public method we want to use:
virtual HRESULT __stdcall GetTheThing (
/*[in]*/ BSTR arg,
/*[out,retval]*/ BSTR * pRetVal ) = 0;
That means that the imported method will expect an input-string of type BSTR, and a pointer to a BSTR for the output string that the imported method will return on success. You can set them up like this, for example:
BSTR thing_to_send = ::SysAllocString(L"My thing, or ... ");
BSTR returned_thing;
Before we can use the imported method, we will have to construct it. From the .tlh file, we see these lines:
namespace MyCSharpClass {
//
// Forward references and typedefs
//
struct __declspec(uuid("48b51671-5200-4e47-8914-eb1bd0200267"))
/* LIBID */ __MyCSharpClass;
struct /* coclass */ TheClass;
struct __declspec(uuid("1ed1036e-c4ae-31c1-8846-5ac75029cb93"))
/* dual interface */ _TheClass;
//
// Smart pointer typedef declarations
//
_COM_SMARTPTR_TYPEDEF(_TheClass, __uuidof(_TheClass));
//
// Type library items
//
struct __declspec(uuid("485b98af-53d4-4148-b2bd-cc3920bf0adf"))
TheClass;
// [ default ] interface _TheClass
// interface _Object
First, we need to use the namespace of the class, which is MyCSharpClass
Next, we need to determine the the smart pointer from the namespace, which is _TheClass + Ptr ; this step is not remotely obvious, as it's nowhere in the .tlh file.
Last, we need to provide the correct construction parameter for the class, which is __uuidof(MyCSharpClass::TheClass)
Ending up with,
MyCSharpClass::_TheClassPtr obj(__uuidof(MyCSharpClass::TheClass));
Step 9 - Initialize COM and test the imported library
You can do that with CoInitialize(0) or whatever your specific COM initializer happens to be.
#include "pch.h"
#include <iostream>
#include <Windows.h>
#import "MyCSharpClass.tlb" raw_interfaces_only
int wmain() {
CoInitialize(0); // Init COM
BSTR thing_to_send = ::SysAllocString(L"My thing, or ... ");
BSTR returned_thing;
MyCSharpClass::_TheClassPtr obj(__uuidof(MyCSharpClass::TheClass));
HRESULT hResult = obj->GetTheThing(thing_to_send, &returned_thing);
if (hResult == S_OK) {
std::wcout << returned_thing << std::endl;
return 0;
}
return 1;
}
Once again, don't panic when Intellisense freaks out. You're in Black Magic, Voodoo, & Thar Be Dragons territory, so press onward!
The absolute best way I have found to do this is create a c++/cli bridge that connects the c# code to your native C++. You can do this with 3 different projects.
First Project: C# library
Second Project: C++/CLI bridge (this wraps the C# library)
Third Project: Native C++ application that uses the second project
I recently created a simple GitHub Tutorial for how to do this here. Reading through that code with a little grit and you should be able to hammer out creating a C++/CLI bridge that allows you to use C# code in your native C++.
As a bonus I added how to wrap a C# event down to a function pointer in C++ that you can subscribe to.
I found something that at least begins to answer my own question. The following two links have wmv files from Microsoft that demonstrate using a C# class in unmanaged C++.
This first one uses a COM object and regasm: http://msdn.microsoft.com/en-us/vstudio/bb892741.
This second one uses the features of C++/CLI to wrap the C# class: http://msdn.microsoft.com/en-us/vstudio/bb892742. I have been able to instantiate a c# class from managed code and retrieve a string as in the video. It has been very helpful but it only answers 2/3rds of my question as I want to instantiate a class with a string perimeter into a c# class. As a proof of concept I altered the code presented in the example for the following method, and achieved this goal. Of course I also added a altered the {public string PickDate(string Name)} method to do something with the name string to prove to myself that it worked.
wchar_t * DatePickerClient::pick(std::wstring nme)
{
IntPtr temp(ref);// system int pointer from a native int
String ^date;// tracking handle to a string (managed)
String ^name;// tracking handle to a string (managed)
name = gcnew String(nme.c_str());
wchar_t *ret;// pointer to a c++ string
GCHandle gch;// garbage collector handle
DatePicker::DatePicker ^obj;// reference the c# object with tracking handle(^)
gch = static_cast<GCHandle>(temp);// converted from the int pointer
obj = static_cast<DatePicker::DatePicker ^>(gch.Target);
date = obj->PickDate(name);
ret = new wchar_t[date->Length +1];
interior_ptr<const wchar_t> p1 = PtrToStringChars(date);// clr pointer that acts like pointer
pin_ptr<const wchar_t> p2 = p1;// pin the pointer to a location as clr pointers move around in memory but c++ does not know about that.
wcscpy_s(ret, date->Length +1, p2);
return ret;
}
Part of my question was: What is better? From what I have read in many many efforts to research the answer is that COM objects are considered easier to use, and using a wrapper instead allows for greater control. In some cases using a wrapper can (but not always) reduce the size of the thunk, as COM objects automatically have a standard size footprint and wrappers are only as big as they need to be.
The thunk (as I have used above) refers to the space time and resources used in between C# and C++ in the case of the COM object, and in between C++/CLI and native C++ in the case of coding-using a C++/CLI Wrapper. So another part of my answer should include a warning that crossing the thunk boundary more than absolutely necessary is bad practice, accessing the thunk boundary inside a loop is not recommended, and that it is possible to set up a wrapper incorrectly so that it double thunks (crosses the boundary twice where only one thunk is called for) without the code seeming to be incorrect to a novice like me.
Two notes about the wmv's. First: some footage is reused in both, don't be fooled. At first they seem the same but they do cover different topics. Second, there are some bonus features such as marshalling that are now a part of the CLI that are not covered in the wmv's.
Edit:
Note there is a consequence for your installs, your c++ wrapper will not be found by the CLR. You will have to either confirm that the c++ application installs in any/every directory that uses it, or add the library (which will then need to be strongly named) to the GAC at install time. This also means that with either case in development environments you will likely have to copy the library to each directory where applications call it.
I did a bunch of looking around and found a relatively recent article by Microsoft detailing how it can be done (there is a lot of old infomration floating around). From the article itself:
The code sample uses the CLR 4 hosting APIs to host CLR in a native C++ project, load and invoke .NET assemblies
https://code.msdn.microsoft.com/CppHostCLR-e6581ee0
Basically it describes it in two steps:
Load the CLR into a process
Load your assembly.
I have been tasked with creating a Wrapper for a C-library to be used in C#. I have no control over the C-library's source code and I only have access to its header file and to the static library file (.lib).
I have followed several tutorials and got this working when creating an unmanaged C++ class which is wrapped using CLI/C++ and used in C#. No problem. The problem I am facing know though, is as C does not use namespaces, I have trouble figuring out how to tell the compiler when I want to call the function from the .lib file itself, rather than my identically named wrapper function. If it helps understanding, my header file only consists of function definitions, typedefs (structs, enums), but no classes (not even sure if C headers usually do?).
What I have done:
Created a VS C++ CLR Class Library (.NET Framework) project
Linked my .lib file to all configurations in linker->inputs as an additional dependency.
Created two files: Wrapper.h and Wrapper.cpp.
#included the header file corresponding to my .lib in the Wrapper.h file
This is where I get a bit confused, mostly due to the tutorials all covering how to link a C++ library rather than a C library. The difference there being the lack of namespace in C, and (in my case) the lack of class.
Uncertainties:
I do not know if I need a ref class Analytics{} in my Wrapper.h or not. I assume I do if I want to use all the functions statically, but as there is no corresponding class in the C library, can I just name this whatever I want?
In order to properly link the C library in my header file (Wrapper.h), I need to use the same function definition as in the original header file. Do I repeat the use of "extern" and such keywords? Can I freely add static and accessibility modifiers?
At this point I want to "implement" the function in the Wrapper.cpp file. Here my problem about identical function names comes in. The function I want to implement has the same name in the original header file as it does in the Wrapper header file (obviously, as it would not work otherwise, right?). The wrapper header file contains a namespace and a class (for now class name is Analytics) so I can declare the function as Analytics::void SanSetApplicationContext(){...}, but as the original C library header file does not contain classes or namespaces, there is no way for me to call that function and distinguishing between them. The C++ compiler always prefers the local definition and I am stuck with a function calling itself for all eternity. I hope you understand my point.
I am probably doing something wrong and/or misunderstanding something, but how would you guys suggest I approach this issue? I will append my files contents below. In the files I have so far only tried implementing a single function. Code should be fixed and hopefully working
Wrapper.h
#pragma once
using namespace System;
namespace Wrapper {
public ref class Analytics
{
public:
static void SanSetApplicationContext(String^ ctx);
};
}
Wrapper.cpp
#include "pch.h"
#include "Wrapper.h"
#include "../SWA_lib/Analytics.h"
namespace Wrapper {
void Analytics::SanSetApplicationContext(String^ ctx) {
//Convert String^ to const char*
msclr::interop::marshal_context mCtx;
const char* convertedStr = mCtx.marshal_as<const char*>(ctx);
::SanSetApplicationContext(convertedStr);
}
}
Analytics.h
...
extern void SanSetApplicationContext(const char *ctx);
...
Update
Updated the code to reflect my changes made based on your comments. Thanks!
Update 2
#Bodo asked me to explain another issue of mine, which is how I would handle wrapping functions that return opaque handles. The example used is the following: typedef struct SanEvent_s *SanEvent; which is found in my C header file. So basically, this library provides an API. The API execution always starts with a call to an Initialize(); function, and ends with a call to the Terminate(); function. I have no previous experience of using this API, but from the documentation, I assume that all objects, references and what not are freed/destroyed when Terminate() is called, as none of their examples show destroying objects.
Now, creating a SanEvent is done like this (according to documentation):
SanEvent event;
event = SanNewEvent("The Main Event");
This opaque handle is considered protected on the C# side, so there does not seem to be a way for me of returning it all the way there. My idea is to keep the events in some kind of Collection, in the C++/CLI wrapper where the type can be used, and only return the index of the Event to C# (The index the even would have in a List or something). I am not sure this is a good idea, but this is as far as I have come with my plan. Something that represents a SanEvent needs to be returned to C# as I need to be able to reference the event in the future, in order to add additional information to the event via other functions. This idea would of course need tailored "helper functions" on the C++ side which mediate between C# and C. I am sorry if the information is vague, but I don't really have a lot to go on myself as of now.
Adding "::" to the beginning of a function call tells the compiler to use the function found in global namespace rather than local namespace/class. So:
namespace Wrapper {
void Analytics::SanSetApplicationContext(const char *ctx) {
::SanSetApplicationContext(ctx);
}
}
Should call the c version correctly
I have a C++ console Exe which does some progamming. Now i wanted to write a C# GUI which does some of the programming that the C++ exe does. I was thinking of few approaches,
Write the C# GUI with all programming in C++ done from scratch.(I do not want to do this for the amount of rework it entails)
Build a C++ dll which does the programming and have it imported in GUI app.(Now here i have a concern. How do i capture the output of the routines in c++ dll and display it in GUI? Should i return the output as string for every routine that the app calls.? Since i dont know managed c++ iam going to build an unmanaged C++ dll. )
Building a C++/CLI dll really isn't that hard. You basically use unmanaged C++ code except that you define a "public ref class" which hosts the functions you want the C# code to see.
What kind of data are you returning? Single numbers, matrices of numbers, complex objects?
UPDATE: Since it has been clarified that the "output" is iostreams, here is a project demonstrating redirection of cout to a .NET application calling the library. Redirecting clog or cerr would just require a handful of additional lines in DllMain patterned after the existing redirect.
The zip file includes VS2010 project files, but the source code should also work in 2005 or 2008.
The iostreams capture functionality is contained in the following code:
// compile this part without /clr
class capturebuf : public std::stringbuf
{
protected:
virtual int sync()
{
// ensure NUL termination
overflow(0);
// send to .NET trace listeners
loghelper(pbase());
// clear buffer
str(std::string());
return __super::sync();
}
};
BOOL WINAPI DllMain(_In_ HANDLE _HDllHandle, _In_ DWORD _Reason, _In_opt_ LPVOID _Reserved)
{
static std::streambuf* origbuf;
static capturebuf* altbuf;
switch (_Reason)
{
case DLL_PROCESS_ATTACH:
origbuf = std::cout.rdbuf();
std::cout.rdbuf(altbuf = new capturebuf());
break;
case DLL_PROCESS_DETACH:
std::cout.rdbuf(origbuf);
delete altbuf;
break;
}
return TRUE;
}
// compile this helper function with /clr
void loghelper(char* msg) { Trace::Write(gcnew System::String(msg)); }
So you just want to call c++ library from managed .net code?
Then you would need to either build a COM object or a p-invokable library in c++. Each approach has it's own pros and cons depending on your business need. You would have to marshall data in your consumer. There are tons and tons of material on both concepts.
Possibly relevant: Possible to call C++ code from C#?
You could just write a C# GUI wrapper (as you suggest in option 2) and spawn the C++ process; however, this will be a little slow (I don't know if that matters).
To run your C++ exe and capture the output you can use the ProcessRunner I put together. Here is the basic usage:
using CSharpTest.Net.Processes;
partial class Program
{
static int Main(string[] args)
{
ProcessRunner run = new ProcessRunner("svn.exe", "update");
run.OutputReceived += new ProcessOutputEventHandler(run_OutputReceived);
return run.Run();
}
static void run_OutputReceived(object sender, ProcessOutputEventArgs args)
{
Console.WriteLine("{0}: {1}", args.Error ? "Error" : "Output", args.Data);
}
}
See the first comment in this page to redirect stderr
Probably the best way to go here is use P/Invoke or Platform Invoke. Depending on the structure or your C++ dll interface you may want to wrap it in a pure C interface; it is easiest if your interface uses only blittable types. If you limit your dll interface to blittable types (Int32, Single, Boolean, Int32[], Single[], Double[] - the basics) you will not need to do any complex marshaling of data between the managed (C#) and unmanaged (C) memory spaces.
For example, in your c# code you define the available calls in your C/C++ dll using the DllImport attribute.
[DllImport, "ExactDllName.dll"]
static extern boolean OneOfMyCoolCRoutines([In] Double[] x, [In] Double[] y, [Out] Double result)
The little [In]'s and [Out]'s are not strictly required, but they can speed things along. Now having added your "ExactDllName.dll" as a reference to your C# project, you can call your C/C++ function from your C# code.
fixed(Double *x = &x[0], *y = &y[0] )
{
Boolean returnValue = OneOfMyCoolCRoutines(x, y, r);
}
Note that I'm essentially passing pointers back and fourth between my dll and C# code. That can cause memory bugs because the locations of those arrays may be changed by the CLR garbage collector, but the C/C++ dll will know nothing of it. So to guard against that, I've simply fixed those pointers in my C#, and now they won't move in memory while my dll is operating on those arrays. This is now unsafe code and I'll need to compile my C# code w/ that flag.
There are many fine details to language interop, but that should get you rolling. Sticking to a stateless C interface of blittable types is a great policy if possible. That will keep your language interop code the cleanest.
Good luck,
Paul
How to make a native API to be PInvoke friendly?
there are some tips on how to modify native-programs to be used with P/Invoke here. But before I even write a native programs, what are the things I should look out to make my programs/library PInvoke friendly?
using C or C++ are fine.
update:
if I write a C API, what are the things I have to do so that It is P/Invoke-able using C# syntax like the following:
[DLLimport("MyDLL.dll")]
is it possible to do the same with native C++ code/library?
Summary/Rephrase of Some Tips to make a P/Invoke friendly native-API:
+ the parameters should be of native types (int, char*, float, ...)
+ less parameters is better
+ if dynamic memory is allocated and passed to managed code, make sure to create a "cleaner" function which is also p/invoked
+ provide samples and/or unit tests that illustrate how to call the API from .NET
+ provide C++/CLI wrapper
Instead of using P/Invoke, if you are controlling the native library yourself, you can write a set of C++/CLI classes that wrap the native calls. In many cases, this will perform better than using platform invoke, and you get the added benefit of type correctness. For example, if you have some sort of C API like the following (it doesn't do anything useful, I just added pointers and structs to reinforce the fact that it is native code):
struct SomeStruct {
int a, b;
int* somePtr;
};
int foo(struct SomeStruct* a, int b) {
*a->somePtr = a->a + a->b;
return a->b * *a->somePtr + b;
}
You can create a C++/CLI class to wrap it:
public ref class MyNativeAPI {
private:
SomeStruct* x;
public:
MyNativeAPI() {
x = new SomeStruct;
}
~MyNativeAPI() {
delete x;
}
int Foo(int a) {
pin_ptr<SomeStruct*> ptr = this->x;
return foo(ptr, a);
}
}
Then, you can call this in C#:
MyNativeAPI a = new MyNativeAPI();
if(a.Foo(5) > 5) { ... };
You'll have to read more on C++/CLI to understand the new controls you have over both the managed heap and the native heap, and the caveats to mixing the two (like the pin_ptr I used above), but overall it's a much more elegant solution to accomplishing native interop in .NET.
By definition every native function can be p/invoked from managed code. But in order to be p/invoke friendly a function should have as few parameters as possible which should be of native types (int, char*, float, ...). Also if a function allocates memory on some pointer that is returned to managed code, make sure you write its counter part that will free the pointer as managed code cannot free memory allocated from unmanaged code.
Provide an example of correctly calling it from C# or .NET, even better provide a .NET class that wraps all your methods
Writing a simple unit test with nunit
that proves your code works correctly
when called from .Net would be a great
way of doing it.
Also remember that the .NET developers that are likely to be calling your code are unlikely to know much about C++, or don’t know the sizes of different data types etc or how these types map to the PInvoke attributes.
Above all think about how you wish your clients code to look and then design a API that allows it.
Bit of a history lesson here. I'm working on a legacy C++/MFC application and am trying to start a incremental modernization by pushing components written in C# (WinForms and later WPF).
I'm stucking using .Net/1.1 and VS/2003 for many reasons which are impossible to resolve in the near future.
Currently, as a proof of concept, something like this works:
#pragma push_macro("new")
#undef new
WinFormA::Form1* myform;
myform = __gc new WinFormA::Form1();
myform->ShowDialog();
#pragma pop_macro("new")
The problem I'm having is this - I need the unmanaged C++/MFC code to pass a callback pointer into the managed C# WinForm code so that I can capture user interactions and have them processed by the application.
I've looked at some articles such as this MSDN article but it doesn't work in VS/2003 (the compiler doesn't like the delegate syntax).
Are there any other options? I don't think I can use DLLImport since I need to interact with the specific application instance not a flat API.
Thanks!
If the other answers don't work out, you could always write a C wrapper to flatten the classes. For example, if the C++ class is:
class TheClass {
public:
TheClass(int Param);
~TheClass();
bool SomeFunction(int Param1,int Param2);
};
I'll write a wrapper:
extern "C" void *TheClass_Create(int Param) {
return (void*) new TheClass(Param);
}
extern "C" void TheClass_Destroy(void *This) {
delete (TheClass*) This;
}
extern "C" bool TheClass_SomeFunction(void *This,int Param1,int Param2) {
return ((TheClass*) This)->SomeFunction(Param1,Param2);
}
Because the wrapper is straight C, you can P/Invoke in C# to your heart's content (the void *This should become an IntPtr to ensure compatibility if you move to 64-bit). Sometimes, if I'm really ambitious, I'll actually write a C# wrapper around the P/Invokes to 're-classify' the thing.
I already forgot .NET 1.*, but:
Define necessary interfaces and register your .NET components as COM objects. .NET utilities will usually provide reasonably good marshaling code.
If possible, access them as COM objects from C++ application without any Managed C++ at all. (Use interface pointers instead of functions for callbacks).
If COM is not an option, use .NET Reflector to see what's going on inside auto-generated interop assemblies - this might give an insight on how to do the same thing manually.
I have never tried it by myself, but did you check RuntimeMethodHandle struct which is definitely exists in .net1?
SomeDelegate Handler = new SomeDelegate(SomeMethod);
IntPtr HandlerPtr = Handler.Method.MethodHandle.GetFunctionPointer();
And some copy-paste from MSDN's description .net2 Marshal::GetDelegateForFunctionPointer Method:
In versions 1.0 and 1.1 of the .NET Framework, it was possible to pass a delegate representing a managed method to unmanaged code as a function pointer, allowing the unmanaged code to call the managed method through the function pointer. It was also possible for the unmanaged code to pass that function pointer back to the managed code, and the pointer was resolved properly to the underlying managed method.