Including headers from an unmanaged C++ code inside C++/CLI code - c++-cli

I'm writing a CLR wrapper for an unmanaged C++ library.
There are two files I'm including from the unmanaged lib:
//MyCLIWrapper.h
#include "C:\PATH\TO\UNMANAGED\Header.h"
#include "C:\PATH\TO\UNMANAGED\Body.cpp"
Then I'm writing CLI implementations for the unmanaged library functions:
//MyCLIWrapper.h
// includes ...
void MyCLIWrapper::ManagedFunction()
{
UnmanagedFunction(); // this function is called successfuly
}
However, if my Unmanaged function contains calls to other functions that are defined in other unmanaged header files. This causes a compiler linkage error.
If I add includes to the unmanaged headers that define these functions, my errors get resolved. However, there is a lot of functions, and a lot of includes required.
Is there a different way to approach this?
EDIT:
P.S.
My managed code is in a separate Visual Studio project (output - DLL), and the compile settings are set to /CLR. Unmanaged code is in a separate Win32 project (output - DLL).
Also, after more research I concluded that theoretically I could set my Win32 unmanaged project to CLR and just add my managed classes and headers in there as an entry point, and then it would all compile into a single DLL file. That would probably solve (?) the linkage errors. However, I would prefer to preserve the loose coupling as well as the additional series of problems that can raise from setting my unmanaged project to CLR.
EDIT #2:
The unmanaged class that I'm referencing (body.cpp, header.h) contains includes to the required files that define the functions that are causing the problems. However, my managed code doesn't pick up on the includes that are in the unmanaged body.cpp and header.h.

Linker errors are a different kettle of fish from compiler errors. You forgot to document the exact linker errors you see, but a very common mishap when you compile code with /clr in effect is that the default calling convention for non-C++ member function changes. The default is __clrcall, a convention that's optimized for managed code. While functions compiled without /clr defaults to __cdecl. Which changes the way the function name is mangled. You see this back in the linker error message, is shows that it is looking for a __clrcall function and can't find it.
You'll need to either explicitly declare your functions in the .h file with __cdecl. Or tell the compiler that these functions are not managed code. Which is the best way to tackle it:
#pragma managed(push, off)
#include "unmanagedHeader.h"
#pragma managed(pop)

Solution was fairly simple:
I added both unmanaged and managed projects to a single solution in Visual Studio.
Set the unmanaged project's "Configuration Type" to "Static Library" (.lib).
Right click on the managed project -> References -> Add Reference -> Projects -> -> Add Reference.
Then in my managed class, I include the header.h (only) just like I did in my question.
Compiled successfully!
Thank you

Related

Linker error when calling function in native C++ from a c++/cli project

I am trying to call functions in c++ from C# and to do this, I created a C++/CLI project to wrap C++ codes.
My code compiles, but during linkage, I am getting error that linker can not find methods which are defined in c++ code.
The c++ code is a static library and I add a reference to it in C++/CLI project (common properties -> framework and references -> add new reference)
My questions:
Is there anything else should I do?
is adding reference in this sections means that the reference is a .net assembly? Or could it be a reference to a static library.
Edit 1
I am sing VS 2012 on windows 7 64bit
Linker Error:
Error 3 error LNK2019: unresolved external symbol "public: static class MyFile __cdecl MyFile::ReadMyFile(char *)" (?ReadMyFile#MyFile##$$FSA?AV1#PAD#Z) referenced in function "public: static class MyFileWrapper::MyFileWrapper ^ __clrcall MyFileWrapper::MyFileWrapper::ReadMyFile(class System::String ^)" (?ReadMyFile#MyFileWrapper#1#$$FSMP$AAV11#P$AAVString#System###Z) MyFileWrapper.obj
You didn't post the linker error message, that makes it difficult to answer this question accurately. The most common causes:
Forgetting to tell the compiler that the function is a native function and not a managed one. You can tell from the linker error message when you see it using the __clrcall calling convention, native code normally uses the __cdecl calling convention. You fix that by putting #pragma managed(push, off) before the #include, #pragma managed(pop) after it.
Trying to link a static library that was compiled with /clr in effect. That's not supported without otherwise drawing a complaint about that when you build the library, unfortunately. The equivalent is already well supported by the CLR, it binds libraries at runtime. You fix that by creating a class library project instead so you'll get a DLL after building it. Use Add Reference to import the declarations from that assembly instead of using #include.
Forgetting to tell the linker that it needs to link an unmanaged static library or import library. Using Add Reference is supported in VS2010 and up, on earlier versions of VS you need to use the Linker, Input, Additional Dependencies setting or use #pragma comment(lib, "name") in your source code.
$$F part of the given mangled name is a marker of function modifier , that means managed function [Managed C++ or C++/CLI], according to "Visual C++ name mangling".
I faced very similar problem. I figured out that in my case there was:
<ProjectReference Include="ProjName\ProjName.vcxproj">
<ProjectReference Include="..\ProjName\ProjName.vcxproj">
I've just fixed that and made rebuild and it helped me.

Using BoostTest with C++/CLI : possible or not?

I have a Visual Studio project containing the code of a program (a model). I have created an other project to put the boost tests in it.
The problem is that I can't get it to work.
I can use the boost tests alone in the project, but as soon as I want to link (reference, etc) to the first project (the one I want to run the tests on), the boost test project won't compile :
1>E:\boost_1_53_0\boost/detail/interlocked.hpp(99): warning C4164: '_InterlockedExchange' : fonction intrinsèque non déclarée
1>E:\boost_1_53_0\boost/detail/interlocked.hpp(100): warning C4164: '_InterlockedExchangeAdd' : fonction intrinsèque non déclarée
1>E:\boost_1_53_0\boost/smart_ptr/detail/spinlock_w32.hpp(62): error C3861: '_InterlockedExchange' : identificateur introuvable
I read there that you can't
your code is not C++ but "C++ CLI" and thus you cant use boost. C++ does not have a System namespace. In each .cpp file you can either use C++/CLI (and therefore the System namespace) OR boost. If you want to use the System namespace you have to enable the "Common Langauge Runtime Support", for boost you have to disable it
>> Can anyone confirm that it is not possible to use Boost with a C++/CLI program ?
Yes, it is possible.
First you have to change your C++/CLI project to /clr (/clr:pure or /clr:safe won't work). This allows your project to run in mixed mode, i.e. to run both native C++ and managed code.
Read more on msdn.microsoft.com
Set up Boost.Test for Visual Studio (add the path to the .h of Boost, and add the .lib path in the linker ; you might have to compile Boost because in some cases it's not "header only") ; here is a good tutorial itee.uq.edu.au
That's it, you can write and compile your tests.
However, due to a bug in the compiling (linking, most likely) process of the C++/CLI code and Boost, I haven't been able to put the Boost tests in a different project ; so I had to put the unit tests within the code of the program itself (in seperate .cpp files though, which is an acceptable solution).
The basic problem is that in C++ (non-CLI) code like boost, you cannot hold any managed references or pointers.
I have found that for C++/CLI code, it's usually preferable to use a C# testing framework. C# can talk to the C++/CLI part, which can talk to the pure C++ part. In addition, most use-cases for C++/CLI are wrapping C++ or C code for .Net, so it's a natural choice to test the interface that .Net can see.
As an example, I have a project where all the interfaces are specified in C#. Some implementations use C++/CLI and call into the boost libraries, others are pure C#. The unit tests are generic, with the generic parameter being the actual implementation under test.
Example for MSTest/vstest:
public class MyTest< T > where T : IMyInterface
{
[TestMethod]
public void foo() {...}
}
[TestClass]
public class TestCppCli : MyTest< CppCliImpl > {}
[TestClass]
public class TestCSharp : MyTest< CSharpImpl> {}

c++/cli interface header file

I have a C++ project (visual studio 2010) which consists of native code and c++/cli code as well. I cant compile the whole project with /clr, so I just do it for the respective c++/cli files. My Problem is that a header file cant be compiled with /clr, but I want to make some c++/cli functions reusable within the whole project and therefor define the method prototypes in a header file to include it in every file where I need it. Is there a solution? I have tried to define some mixed code method prototypes in a header file, but /clr must be switched on for that to compile.
Here is my example:
Test.h
#include <Windows.h>
#include <vector>
#include <string>
using std::vector;
using std::string;
#include <msclr/marshal.h>
#pragma managed
using namespace msclr::interop;
using namespace System;
using namespace System::IO;
using namespace System::Runtime::InteropServices;
public ref class Test
{
public:
int Foo();
};
Test.cpp
#include "Test.h"
int Test::Foo()
{
return 4;
}
Intellisense is complaining with errors in Test.h like c++/cli must be enabled to use #using. But I think this is negligible and it would compile anyway.
Compilation aborts with a Linker Error (sry, i have german VS version)
Fehler 6 error LNK1255: Fehler bei Verknüpfung aufgrund von Metadatenfehlern.
Fehler 4 error LNK2022: Fehler bei Metadatenoperation (8013118D) : Duplizierte Typen (_PROPSHEETPAGEA) wurden gefunden, aber die Typenlayoutinformationen sind nicht konsistent: (0x02000198).
Fehler 5 error LNK2022: Fehler bei Metadatenoperation (8013118D) : Duplizierte Typen (_PROPSHEETPAGEW) wurden gefunden, aber die Typenlayoutinformationen sind nicht konsistent: (0x020001d1).
I definitely dont have a duplicate class "Test" elsewhere, so I dont know where the duplicate comes from. What are typelayout informations and why are they not consistent?
I think you've all missed the point.
You can easily compile a native project with some /clr classes. (For example: A native DLL will still function like a native DLL, however, it can also be loaded into C#, and it's /clr compiled classes can then be accessed in C#.)
That's why such an option exist at the file level. (Right click .cpp: Properties->C\C++->Common Language Runtime Support- /clr)
The problem is:
Communicating between native\managed classes, since .H files cannot be set to use /clr, those cannot be used to reference a managed class elsewhere including other /clr files within the same project. (ie, you can create /clr files, but, they can't talk to each other, nor can you reference them within native portions of the project.)
The best solution I can find is to create a "glue" C# .dll file.
Create a new C# class library, add the Native DLL as a reference, then compile.
Now, in your native project, you can load the C# DLL, and access the natives /clr stuff through it. (The managed code you reference this way can be used with native\managed code.)
It's very possible, but, I cannot find a straightforward way to accomplish this.
That's what the topic is about, there seems to be no way to reference /clr classes due to header files not working when you set /clr at the file level. (ie, a header cannot contain /clr code unless the WHOLE project is set to /clr.)
There must be a way to reference /clr stuff without headers, or C++\CLI is just broken, I can easily load native code into /clr files by using pragma + headers, however, the reverse is looking impossible short of my "glue" solution.
That is what I believe this topic is about.
My method works, but, it's very tricky to get right, and compilation is a pain due to circular dependencies, etc,.
I really hope there is a proper way to do this, I've been looking, and my search led me here...
The real solution, would be to make .h files support /clr, then you could define your managed class in the header, and be able to freely reference it using standard methods, like include\using\pragma, etc,.
Perhaps you're looking for
#if __cplusplus_cli
Documented here on MSDN

Create frameworks for iOS bundled with unity data and its library

This is regarding creating the framework in iOS, as I have a bundle of unity which I want to create a framework, with data with-holding and linking library from Unity as libiPhone-lib.a. So without adding any library in the bundle target, the compilation works fine, if I include libiPhone-lib.a file, it generates a warning as:
warning: implicit declaration of function 'UnitySendMessage'
The UnitySendMessage is a function which is being called from the dedicated libiPhone-lib.a framework.
Any suggestions regarding this concern will be really appreciated.
Thanks.
This error means that, in the file where it occurred, UnitySendMessage was called without the compiler having seen a declaration for the function. You need to edit the file and #import the header that contains UnitySendMessage (or #include if it is a .c file)
.
The Unity folks seem to have neglected to include a header declaring this function. You can either declare it yourself, or just ignore the warning.

STA, MTA conflict warning Important?

I recently started writing a C++/CLI wrapper for a native c++ library. I'm now getting this compile warning
"warning LNK4249: directive '/CLRTHREADATTRIBUTE:STA' conflicts with command line; ignored"
My c++/cli wrapper is set up for MTA in the linker's command line arguments, but I have no idea what file or project is trying to give the STA directive.
I did enough reading to get worried about .NET forcing libraries to become multi-threaded. I've read that this mostly affects my application's use of COM, but I am not really sure if or where my DLL uses COM. I use the interop services to marshal string data and am using 'msclr\auto_gcroot.h' to point to managed classes from unmanaged ones. In the native c++ library that is being wrapped, I include the following headers:
#include <afxwin.h> // MFC core and standard components
#include <afxext.h> // MFC extensions
#include <afxmt.h>
#include "Winsock2.h."
#include <time.h>
Does anybody have any advice that could help me avoid painful experiences in the future, or should I just not worry about it?
So far so good. I haven't seen any real problems with this; I think it is just because MFC is a single threaded library, so it wants to compile that way. So, for my case, I think as long as I treat all MFC objects and such as not thread-safe I'll be okay.