c++/cli interface header file - header

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

Related

Problems with midl.exe and cppwinrt.exe from CMake

This is somewhat of a follow-on to How to use midlrt.exe to compile .idl to .winmd?
I have this in my CMakeLists.txt . My questions are less about the CMake logic and more about the output of the midl and cppwinrt commands, and subsequent errors in compiling and linking. I suspect maybe I'm missing some command-line options.
# Pathnames for WinRT References
set (WINSDKREFDIR "$ENV{WindowsSdkDir}References\\$ENV{WindowsSDKVersion}")
# Remove trailing \ from $ENV{WindowsSDKVersion}
string (REGEX MATCH "[^\\]*" WINSDKVER $ENV{WindowsSDKVersion})
# COMMAND lines wrapped in this post for readability, not wrapped in the actual CMakeLists.txt
add_custom_target (MYLIB_PREBUILD ALL
COMMAND midl /winrt /ns_prefix /x64 /nomidl
/metadata_dir
"${WINSDKREFDIR}windows.foundation.foundationcontract\\3.0.0.0"
/reference
"${WINSDKREFDIR}windows.foundation.foundationcontract\\3.0.0.0\\Windows.Foundation.FoundationContract.winmd"
/reference
"${WINSDKREFDIR}Windows.Foundation.UniversalApiContract\\8.0.0.0\\Windows.Foundation.UniversalApiContract.winmd"
/out "${MYDIR}\\GeneratedFiles" "${MYDIR}\\MyClass.idl"
COMMAND cppwinrt
-in "${MYDIR}\\GeneratedFiles\\MyClass.winmd"
-ref ${WINSDKVER} -component -pch "pch.h" -out "${MYDIR}\\GeneratedFiles"
)
add_dependencies (MYLIB MYLIB_PREBUILD)
In the cppwinrt command, I've tried different forms of -ref [spec] and -pch options, but seem to get the same results regardless. These are the problems I've run into:
MIDLRT generates a header file "MyClass.h" with several problems:
It #includes <windows.h>, which ultimately #defines preprocessor macros for GetClassName and GetCurrentTime that cause compiler errors in WinRT functions with those names.
I spent some hours tracking that down and learning to compile with #define COM_NO_WINDOWS_H to prevent that.
It #includes non-existent *.h files from WinRT References Contracts directories instead of the Include directories:
#include "C:\Program Files (x86)\Windows Kits\10\References\10.0.18362.0\Windows.Foundation.FoundationContract\3.0.0.0\Windows.Foundation.FoundationContract.h"
#include "C:\Program Files (x86)\Windows Kits\10\References\10.0.18362.0\Windows.Foundation.UniversalApiContract\8.0.0.0\Windows.Foundation.UniversalApiContract.h"
So I made a copy of this file and replaced those with
#include <winrt/Windows.Foundation.h>
CPPWINRT generates "module.g.cpp" that #includes "MyNamespace.MyClass.h", but does not also generate that .h file. It does generate "MyNamespace/MyClass.h" (note "/" instead of "."), so I created the former .h and simply #include the latter .h from it.
CPPWINRT doesn't generate all of the base headers that I see in Microsoft examples. It generates only headers directly related to MyClass -- e.g., defining the template base class winrt::MyNamespace::implementation::MyClassT<>, the wrapper winrt::MyNamespace::MyClass, etc.
winrt::MyNamespace::factory_implementation::MyClass is not defined. MyClassT<> is defined there, but not MyClass. I find a paradigm for that from a Microsoft example and paste it in:
// Missing from the generated stuff -- derived from a Microsoft example:
namespace winrt::MyNamespace::factory_implementation
{
struct MyClass : MyClassT<MyClass, implementation::MyClass>
{
};
}
I received compiler warnings about inconsistent definitions of CHECK_NS_PREFIX_STATE: in some places it was "always" and in other places it was "never". So now I #define MIDL_NS_PREFIX and #define CHECK_NS_PREFIX_STATE="always"
Now the build gets through the compiler, but I have unresolved external symbols in the linker. I think these things are supposed to be defined inline in a "winrt/base.h", but cppwinrt did not export such a file (as I see in Microsoft examples), and the equivalent file in the system directory contains only prototypes, not bodies:
WINRT_GetRestrictedErrorInfo
WINRT_RoInitialize
WINRT_RoOriginateLanguageException
WINRT_SetRestrictedErrorInfo
WINRT_WindowsCreateString
WINRT_WindowsCreateStringReference
WINRT_WindowsDeleteString
WINRT_WindowsPreallocateStringBuffer
WINRT_WindowsDeleteStringBuffer
WINRT_WindowsPromoteStringBuffer
WINRT_WindowsGetStringRawBuffer
WINRT_RoGetActivationFactory
WINRT_WindowsDuplicateString
Am I missing some simple thing that would resolve all of these problems with missing, incomplete, and incorrect generated files?
The unresolved external symbol errors indicate that you are missing an import library. In this case you will want to link against the WindowsApp.lib umbrella library, that exports the required symbols.
Note that the symbol names you are observing are an artifact of C++/WinRT's requirement to build with as well as without the Windows SDK headers. It addresses this by declaring the imports (with a WINRT_ prefix to prevent clashes with the SDK header declarations), and then maps the renamed symbols using the /ALTERNATENAME linker switch.
I'm not sure this is going to solve all of your issues, but you certainly would want to add ${MYDIR}\\GeneratedFiles to your additional include directories. That should take care of the inability to include the generated headers from the winrt subdirectory (base.h as well as the projected Windows Runtime type headers).
cppwinrt also writes stub implementations for your own types into ${MYDIR}\\GeneratedFiles\\sources, when it processes the .winmd file previously complied from your .idl(s). It's unfortunate, but there's a manual step involved here: You need to copy the generated .h and .cpp files to your source tree, and implement the skeleton implementations. This is required whenever you modify one of your interface definitions.
As a note, the module.g.cpp files generated for my projects do not include any of my custom type headers. Maybe you are using an older version of C++/WinRT (I'm using v2.0.200203.5). I believe this was changed with the introduction of type-erased factories in C++/WinRT version 2.0. Unless you are doing this already, you should use cppwinrt from the Microsoft.Windows.CppWinRT NuGet package as opposed to the binary that (used to) ship with the Windows SDK.

Including headers from an unmanaged C++ code inside C++/CLI code

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

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 C++ namespaces in objective C

I am working on a project that requires a third party library implemented in C++. I have successfully added library to my xcode project, but the problem is that the classes in library contains namespaces and when I try to access methods via namespaces, the XCode generates an error that: "utils undeclared". "utils" is the namespace I am trying to use.
My question is that is there a way to use C++ namespaces in ObjectiveC?
The code I am using to call the method is:
utils::method();
I have tried renaming my ObjectiveC ".m" file to ".mm" file, but the problem remains the same.
We are using C++ libraries in Objective-C and have no problem using C++ namespaces. As Mustafa has indicated, you need to change the Objective-C file extension to .mm to get XCode to recognize the file as Objective-C++. Then you just need to #include (not #import) the C++ headers containing the C++ namespace declarations - this is as you would normally do for 'normal' C++.

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.