I need to CoInitializeSecurity in my application. This is not possible within .NET applications. So I want to implement shim functionality using C++/CLI to call a function which launches a windows form. This works perfect using a .NET Framework dll but not with .NET Core. When I try to add a reference to the C++/CLI project it say's.
I'm able to add the refrence by browsing and select the .NET Core dll but when I run the code it's crashing.
I just saw this link The Future of C++/CLI and .NET Core 3 in this C++/CLI Support in .Net Core stack overflow question asked several years ago.
Any hints appreciated...
Here is the code.
C Project
//This file contains the 'main' function. Program execution begins and ends there.
#include <iostream>
#include <windows.h>
#include "C.h"
_declspec(dllexport) bool LaunchGUICore();
_declspec(dllexport) bool LaunchGUIFwrk();
bool CoInitSecurity(char* resultMsg)
{
HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
if (FAILED(hr))
{
std::snprintf(resultMsg, 200, "COM initialization failed with %ld", hr);
return false;
}
// setup process-wide security context
hr = CoInitializeSecurity(NULL, // we're not a server
-1, // we're not a server
NULL, // dito
NULL, // reserved
RPC_C_AUTHN_LEVEL_DEFAULT, // let DCOM decide
RPC_C_IMP_LEVEL_IMPERSONATE,
NULL,
EOAC_NONE,
NULL);
if (FAILED(hr))
{
if (hr == RPC_E_TOO_LATE)
std::snprintf(resultMsg, 200, "Security initialization failed with too late. hr: %ld", hr);
else
std::snprintf(resultMsg, 200, "Security initialization failed hr: %ld", hr);
return false;
}
std::snprintf(resultMsg, 200, "COM security initialized successfully");
return true;
}
int main()
{
char resultMsg[200];
CoInitSecurity(&resultMsg[0]);
std::cout << resultMsg << "\r\n";
LaunchGUIFwrk();
//LaunchGUICore();
}
C++/CLI Project
#pragma once
#include <string>
#include <msclr\marshal_cppstd.h>
#include <msclr\marshal.h>
using namespace System;
using namespace System::Reflection;
using namespace System::Runtime::InteropServices;
using namespace System::Collections::Generic;
using namespace msclr::interop;
#pragma managed
namespace C
{
public ref class DoWork
{
public:bool LaunchGUICore()
{
return Client::NCO::Bridge::LaunchGUI();
}
public:bool LaunchGUIFwrk()
{
return Client::NET::Bridge::LaunchGUI();
}
};
}
__declspec(dllexport) bool LaunchGUICore()
{
C::DoWork work;
return work.LaunchGUICore();
}
__declspec(dllexport) bool LaunchGUIFwrk()
{
C::DoWork work;
return work.LaunchGUIFwrk();
}
.NET Framework / .NET Core Project
using System.Windows.Forms;
namespace Client.NET
{
public class Bridge
{
public static bool LaunchGUI()
{
Application.Run(new Client());
return true;
}
}
}