How to export a __interface derived class in visual c++? - visual-c++

I want to export a class type that derives from a __interface(only available for Visual c++),which aiming to create c#-like inteface-oriented experience.
//This wiil be defined in a "Famous.h"
__interface IFoo {
int GetNum();
};
//And this is my implementation.
#include "...Famous.h"
class FooImpl : public IFoo
{
public:
FooImpl(int a);
private:
int a;
};
FooImpl::FooImpl(int a)
{
this->a = a;
}
The problem is ,How could I export the 'FoolImpl' type to use it as follows in another project without refrencing the project directly.I tried dllexport,and tons of errors make me exthausted :(.
#include "..Impl.h"
#include "..Famous.h"
void main(){
IFoo* foo = new FooImpl(2);
...
}

Considering of there's no interface in c++,I replaced the __interface with pure virtual class.
//This wiil be defined in a "Famous.h"
#ifdef FAMOUS_EXPORTS
#define XYZAPI __declspec(dllexport)
#else
#define XYZAPI __declspec(dllimport)
#endif
class XYZAPI IFoo {
virual int GetNum() = 0;//void type also valid.
};
//And this is my implementation(Impl.h).
#ifdef IMPL_EXPORTS
#define XYZAPI __declspec(dllexport)
#else
#define XYZAPI __declspec(dllimport)
#endif
#include "...Famous.h"
class XYZAPI FooImpl : public IFoo
{
public:
FooImpl(int a);
private:
int a;
};
FooImpl::FooImpl(int a)
{
this->a = a;
}
And this is my invocation.
#include "..Impl.h"
#include "..Famous.h"
void main(){
IFoo* foo = new FooImpl(2);
...
}

Related

nvcc under linux complains: Contains a vector, which is not supported in device code

I have the following code
#include <cuda.h>
#include <cuda_runtime.h>
#ifdef _MSC_VER
#include <intrin.h>
#else
#include <x86intrin.h>
#endif
//A bitset for the variable assignments
//The state for non existing variable 0 is stored as well, just to avoid +1/-1 adjustments
struct Atom_t {
enum where { device, host};
enum BoolOp {opXor, opOr, opAnd };
public: //TODO make private later
int VarCount;
bool isValid;
union {
uint32_t raw[1]; //don't worry about alignment, the compiler will not use aligned read/writes anyway.}
uint64_t raw64[1];
__m256i avxraw[1];
};
public:
__host__ __device__ friend bool operator==(const Atom_t& a, const Atom_t& b);
};
__host__ __device__ bool operator==(const Atom_t& a, const Atom_t& b) {
const auto IntCount = a.IntCount();
if (IntCount != b.IntCount()) { return false; }
#ifdef __CUDA_ARCH__
__shared__ bool isDifferent;
isDifferent = false;
for (auto i = ThreadId(); i < IntCount; i += BlockDim()) {
if (a.raw[i] != b.raw[i] || isDifferent) {
isDifferent = true;
break;
}
}
syncthreads();
return !isDifferent;
#else
auto result = true;
#ifdef _DEBUG
for (auto i = 0; i < IntCount; i++) {
if (a.raw[i] != b.raw[i]) { result = false; }
}
#endif
auto AvxCount = a.Avx2Count();
if (AvxCount != b.Avx2Count()) { if (result) { print("Atom_t == is incorrect"); } assert1(!result); return false; }
for (auto i = 0; i < AvxCount; i++) {
const auto packedCompare = _mm256_cmpeq_epi8(a.avxraw[i], b.avxraw[i]);
const auto bitmask = _mm256_movemask_epi8(packedCompare);
if (bitmask != -1) { if (result) { print("Atom_t == is incorrect"); } assert1(!result); return false; }
}
#endif
#ifndef __CUDA_ARCH__
assert(result);
#endif
return true;
}
The compiler complains
Description Resource Path Location Type
"__nv_bool (const Atom_t &, const Atom_t &)" contains a vector, which is not supported in device code
However, the vector is not in device code, only in the host code. How do I make this error go away in NSight Eclipse Edition 9.1 running CUDA 11.
I tried:
#ifdef __CUDA_ARCH__
# define DEAL_II_COMPILER_VECTORIZATION_LEVEL 0
#endif
But that does not work.
However, the vector is not in device code, only in the host code.
The error is coming about due to this line:
__m256i avxraw[1];
which is visible in both the host code and device code compilation trajectory.
According to my testing this may be a possible workaround:
$ cat t32.cpp
#ifdef _MSC_VER
#include <intrin.h>
#else
#include <x86intrin.h>
#endif
#include <iostream>
typedef char dummy[sizeof(__m256i)];
struct Atom_t {
enum where { device, host};
enum BoolOp {opXor, opOr, opAnd };
public: //TODO make private later
int VarCount;
bool isValid;
union {
uint32_t raw[1];
uint64_t raw64[1];
#ifndef FOO //hide the vectorized datastruct from cuda's view
__m256i avxraw[1];
#else
alignas(32) dummy foo[1];
#endif
};
};
int main(){
std::cout << sizeof(__m256i) << std::endl;
std::cout << sizeof(Atom_t) << std::endl;
}
$ g++ t32.cpp -o t32
$ ./t32
32
64
$ g++ t32.cpp -o t32 -DFOO
$ ./t32
32
64
(Fedora Core 29)
The alignas(32) directive is still probably somewhat fragile if the definition of __m256i changes dramatically. And, clearly, the above is not CUDA code in the exact frame that was presented. It would need to be adapted (e.g. replace #ifndef FOO with #ifndef __CUDA_ARCH__)
I'm not suggesting that this code is correct, defect-free, or suitable for any particular purpose; it is mostly code provided by OP. My objective here is to identify issues that I see and are asked about in the question, and suggest possible ways to address those issues. Use this at your own risk.
Found it!
The problem is not the code in the method, the problem is the presence of the _m256i within view of cuda.
The following patch fixes the issue:
struct Atom_t {
enum where { device, host};
enum BoolOp {opXor, opOr, opAnd };
public: //TODO make private later
int VarCount;
bool isValid;
union {
uint32_t raw[1]; //don't worry about alignment, the compiler will not use aligned read/writes anyway.}
uint64_t raw64[1];
#ifndef __CUDA_ARCH__ //hide the vectorized datastruct from cuda's view
__m256i avxraw[1];
#endif
};
Now that nvcc does not see the vectorized datatype it will stop worrying.

C++ Windows Form Application: Attempted to read or write protected memory (unmanaged class)

I'm trying to use Boost library in my C++ Windows Form Application and I always get an exception:
Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
I'm using Visual Studio 2012 and Boost version 1.57.0. Previously I used Boost version 1.56.0 but upgrading didn't solve my issue.
Here are the code:
MyForm.cpp
#include "MyForm.h"
using namespace System;
using namespace System::Windows::Forms;
[STAThread]
void main(cli::array<String^>^ args) {
Application::EnableVisualStyles();
Application::SetCompatibleTextRenderingDefault(false);
TestUnmanaged::MyForm form;
Application::Run(%form);
}
MyForm.h
#pragma once
#include <iostream>
#include <map>
#include <sstream>
#include <cassert>
#include <stdio.h>
#include "ExternalProfileManager.h"
#define DEFAULT_PROFILE_NAME "profile.bin"
#pragma comment(lib, "Ws2_32.lib")
#pragma comment(lib, "lib/edk.lib")
namespace TestUnmanaged {
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
ExternalProfileManager profileManager;
/// <summary>
/// Summary for MyForm
/// </summary>
public ref class MyForm : public System::Windows::Forms::Form
{
public:
MyForm(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
profileManager.load(DEFAULT_PROFILE_NAME);
std::vector<std::string> profileList;
profileManager.listProfile(profileList);
}
ExternalProfileManager.h
#ifndef EXTERNAL_PROFILE_MANAGER_H
#define EXTERNAL_PROFILE_MANAGER_H
#include <boost/serialization/string.hpp>
#include <boost/serialization/map.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/serialization/export.hpp>
#include <boost/serialization/tracking.hpp>
#include <boost/serialization/base_object.hpp>
class ExternalProfileManager
{
ExternalProfileManager(const ExternalProfileManager&) {};
ExternalProfileManager& operator = (const ExternalProfileManager&) {};
protected:
std::map<std::string, std::string > _profiles;
typedef std::map<std::string, std::string >::iterator profileItr_t;
// Boost serialization support
friend class boost::serialization::access;
template <class Archive>
void serialize(Archive& ar, const unsigned int /*file version */)
{
ar & _profiles;
}
public:
ExternalProfileManager();
virtual ~ExternalProfileManager();
virtual bool save(const std::string& location);
virtual bool load(const std::string& location);
virtual bool insertProfile(const std::string& name, const unsigned char* profileBuf, unsigned int bufSize);
virtual bool listProfile(std::vector<std::string>& profiles);
};
//BOOST_CLASS_EXPORT(ExternalProfileManager);
//BOOST_CLASS_TRACKING(ExternalProfileManager, boost::serialization::track_never);
#endif // EXTERNAL_PROFILE_MANAGER_H
ExternalProfileManager.cpp
#include <fstream>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/regex.hpp>
#pragma warning(push)
#pragma warning(disable : 4267) // "conversion from size_t to unsigned int"
#pragma warning(disable : 4996)
#include <boost/archive/archive_exception.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#pragma warning(pop)
#include "ExternalProfileManager.h"
using namespace std;
namespace fs = boost::filesystem;
ExternalProfileManager::ExternalProfileManager()
{
}
ExternalProfileManager::~ExternalProfileManager()
{
}
bool ExternalProfileManager::save(const string& location)
{
ofstream ofs(location.c_str(), ios_base::binary);
if ( !ofs.is_open() ) return false;
try {
boost::archive::binary_oarchive oa(ofs);
oa << *this;
}
catch (boost::archive::archive_exception& )
{
return false;
}
return true;
}
bool ExternalProfileManager::load(const string& location)
{
ifstream ifs(location.c_str(), ios_base::binary);
if ( !ifs.is_open() ) return false;
try {
boost::archive::binary_iarchive ia(ifs);
ia >> *this;
}
catch (boost::archive::archive_exception& )
{
return false;
}
return true;
}
bool ExternalProfileManager::insertProfile(const string& name, const unsigned char* profileBuf, unsigned int bufSize)
{
assert(profileBuf);
// Replace our stored bytes with the contents of the buffer passed by the caller
string bytesIn(profileBuf, profileBuf+bufSize);
_profiles[name] = bytesIn;
return true;
}
bool ExternalProfileManager::listProfile(vector<string>& profiles)
{
profiles.clear();
for ( profileItr_t itr = _profiles.begin(); itr != _profiles.end(); ++itr ) {
profiles.push_back(itr->first);
}
return true;
}
The error occurred in ia >> *this; in ExternalProfileManager::load (thrown in file basic_archive.cpp). So calling profileManager.load(DEFAULT_PROFILE_NAME); from form constructor will trigger the exception.
Calling save will also trigger the same exception but other functions which have no this will work fine.
I tried creating a console application in VS 2012 and call ExternalProfileManager.h and it works perfectly (including save, load, and any other function). Here are the simple console application I created to test it:
Console.cpp
#include <iostream>
#include <map>
#include <sstream>
#include <cassert>
#include <stdio.h>
#include "ExternalProfileManager.h"
#define DEFAULT_PROFILE_NAME "profile.bin"
#pragma comment(lib, "Ws2_32.lib")
#pragma comment(lib, "lib/edk.lib")
ExternalProfileManager profileManager;
int main(int argc, char** argv) {
profileManager.load(DEFAULT_PROFILE_NAME);
std::vector<std::string> profileList;
profileManager.listProfile(profileList);
std::cout << "Available profiles:" << std::endl;
for (size_t i=0; i < profileList.size(); i++) {
std::cout << i+1 << ". " << profileList.at(i);
if (i+1 < profileList.size()) {
std::cout << std::endl;
}
}
return true;
}
profile.bin is generated from calling save function in console application and contain serialized data generated by boost. I can provide the file if it is needed to solve this issue.
I have also tried to create a simple class wrapper but the exception still occurred.
WrapperExternalProfileManager.h
#ifndef WRAPPER_EXTERNAL_PROFILE_MANAGER_H
#define WRAPPER_EXTERNAL_PROFILE_MANAGER_H
#include <string>
#include <vector>
class WrapperExternalProfileManager
{
WrapperExternalProfileManager(const WrapperExternalProfileManager&) {};
WrapperExternalProfileManager& operator = (const WrapperExternalProfileManager&) {};
public:
WrapperExternalProfileManager();
virtual ~WrapperExternalProfileManager();
virtual bool save(const std::string& location);
virtual bool load(const std::string& location);
virtual bool insertProfile(const std::string& name, const unsigned char* profileBuf, unsigned int bufSize);
virtual bool listProfile(std::vector<std::string>& profiles);
};
#endif
WrapperExternalProfileManager.cpp
#include "WrapperExternalProfileManager.h"
#include "ExternalProfileManager.h"
using namespace std;
ExternalProfileManager profileManager;
WrapperExternalProfileManager::WrapperExternalProfileManager()
{
std::cout<<"Constructor WrapperExternalProfileManager"<<std::endl;
}
WrapperExternalProfileManager::~WrapperExternalProfileManager()
{
}
bool WrapperExternalProfileManager::save(const string& location)
{
return profileManager.save(location);
}
bool WrapperExternalProfileManager::load(const string& location)
{
return profileManager.load(location);
}
bool WrapperExternalProfileManager::insertProfile(const string& name, const unsigned char* profileBuf, unsigned int bufSize)
{
return profileManager.insertProfile(name, profileBuf, bufSize);
}
bool WrapperExternalProfileManager::listProfile(vector<string>& profiles)
{
return profileManager.listProfile(profiles);
}
save and load still trigger the exception but other functions work perfectly.
Here are some property of the application which might be helpful:
Linker -> System -> SubSystem: Windows (/SUBSYSTEM:WINDOWS)
General -> Common Language Runtime Support: Common Language Runtime Support (/clr)
I know I have done something incorrectly but I don't know which part. Any suggestion to solve this issue would be appreciated.
Thanks in advance
You're going to have to find the source of your Undefined Behaviour (use static analysis tools, heap checking and divide and conquer).
I've just built your code on VS2013 RTM, using a ultra-simple C# console application as the driver:
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var f = new TestUnmanaged.MyForm();
f.ShowDialog();
}
}
}
This JustWorks(TM).
I created a profile.bin with 100 random profiles of varying length:
#if 1
for (int i = 0; i < 100; ++i)
{
std::vector<uint8_t> buf;
std::generate_n(back_inserter(buf), rand() % 1024, rand);
insertProfile("profile" + std::to_string(i), buf.data(), buf.size());
}
save(location);
#endif
And they are deserialized just fine.
Good luck.
Download the full project here http://downloads.sehe.nl/stackoverflow/q27032092.zip in case you want to fiddle with it (compare the details?)

Passing objects as parameters by another object visual c++

I'm trying to pass an object by reference in c++. I get these errors:
Error 1 error C2061: syntax error : identifier 'Common' graphics.h 6 1 SDLGameDev
Error 2 error C2511: 'void Graphics::CreateWindow(Common &)' : overloaded member function not found in 'Graphics' 4 1 SDLGameDev
I found answers about this area, but not any that covers how to do this:
object1.someFunction(object2);
Here is my code:
//Common.h
#ifndef COMMON_H
#define COMMON_H
#include "SDL.h"
#include "iostream"
class Common{
public:
void Init();
bool GetGameRunState(){ return GameRunState; }
void SetGameRunState(bool x){ GameRunState = x; }
private:
bool GameRunState;
};
#endif
//Commmon.cpp
#include "Common.h"
void Common::Init()
{
if (SDL_Init(SDL_INIT_EVERYTHING) == 0)
{
SetGameRunState(true);
}
else
{
SetGameRunState(false);
}
}
//Graphics.h
#ifndef GRAPHICS_H
#define GRAPHICS_H
class Graphics{
public:
void CreateWindow(Common & co);
};
#endif
//Graphics.cpp
#include "Graphics.h"
#include "Common.h"
void Graphics::CreateWindow(Common & co)
{
if (co.GetGameRunState() == true)
{
std::cout << "TEST for CreateWindow()\n";
}
}
//main.cpp
#include "Common.h"
#include "Graphics.h"
Common co;
Graphics go;
int main(int argc, char * args[])
{
co.Init();
go.CreateWindow(co);
while (co.GetGameRunState() == true)
{
std::cout << "Game is running\n";
SDL_Delay(2000);
break;
}
return 0;
}
You haven't included Common.h in the file Graphics.h so it doesn't know about the class.
#ifndef GRAPHICS_H
#define GRAPHICS_H
#include "Common.h" // You need this line
class Graphics {
public:
void CreateWindow(Common & co);
};
#endif
I would recommend using singletons and put the initialisation of sdl, creation of the renderer and window etc all together in one class. Your question has already been answered.

Visual C++ Errors C2146, C4430

Please help to figure out whats wrong with this code.
main.cpp create Object3D which create Box and pass Object3D* pointer to Box.
And there are errors until i remove Object3D declarations from Box.
main.cpp
#include <iostream>
#include "stdafx.h"
#include "Object3D.h"
int _tmain(int argc, _TCHAR* argv[])
{
Object3D obj;
char c;
std::cin >> c;
return 0;
}
Object3D.cpp
#include "Object3D.h"
#include "Box.h"
Object3D::Object3D()
{}
Object3D::~Object3D()
{}
Object3D.h
#ifndef OBJECT3D_H
#define OBJECT3D_H
#include "Box.h"
class Object3D
{
public:
Object3D();
~Object3D();
private:
Box _box_obj; //<<<---ERROR HERE (C2146, C4430)
};
#endif
Box.cpp
#include "Box.h"
#include "Object3D.h"
int Box::Init(Object3D* _obj)
{
obj = _obj;
}
Box::Box()
{}
Box::~Box()
{}
Box.h
#ifndef BOX_H
#define BOX_H
#include "Object3D.h"
class Box
{
public:
Object3D* obj; //<<<---ERROR HERE (C2143, C4430)
int Init(Object3D* _obj); //<<<---ERROR HERE (C2061)
Box();
~Box();
};
#endif
Change Box.h:
#ifndef BOX_H
#define BOX_H
// forward reference possible since the class is not dereferenced here.
class Object3D;
class Box
{
public:
Object3D* obj;
int Init(Object3D* _obj);
Box();
~Box();
};
#endif
The class definition does not use any member of Object3D. Therefore you don't need to know the definition of Object3D but just the fact that it is a class. The forward reference is sufficient and an appropriate tool to resolve a circular dependency.
BTW: The circular reference of object usually includes some "master" objects that own the other objects. It makes sense to change the member name to show the relation rather the type. I would suggest a
Object3D* owner;
when the box owns the obj.

Problems with nested lambdas in VC++

Does anyone know why this code is not compilable with VC++ 2010
class C
{
public:
void M(string t) {}
void M(function<string()> func) {}
};
void TestMethod(function<void()> func) {}
void TestMethod2()
{
TestMethod([] () {
C c;
c.M([] () -> string { // compiler error C2668 ('function' : ambiguous call to overloaded function)
return ("txt");
});
});
}
Update:
Full code example:
#include <functional>
#include <memory>
using namespace std;
class C
{
public:
void M(string t) {}
void M(function<string()> func) {}
};
void TestMethod(function<void()> func) {}
int _tmain(int argc, _TCHAR* argv[])
{
TestMethod([] () {
C c;
c.M([] () -> string { // compiler erorr C2668 ('function' : ambiguous call to overloaded function M)
return ("txt");
});
});
return 0;
}
This is a bug of the VC++ Compiler.
https://connect.microsoft.com/VisualStudio/feedback/details/687935/ambiguous-call-to-overloaded-function-in-c-when-using-lambdas
You did not post the error message, so by looking into my crystal ball I can only conclude that you suffer those problems:
Missing #includes
You need at the top
#include <string>
#include <functional>
Missing name qualifications
You either need to add
using namespace std;
or
using std::string; using std::function;
or
std::function ...
std::string ...
Missing function main()
int main() {}
Works with g++
foo#bar: $ cat nested-lambda.cc
#include <string>
#include <functional>
class C
{
public:
void M(std::string t) {}
void M(std::function<std::string()> func) {}
};
void TestMethod(std::function<void()> func) {}
void TestMethod2()
{
TestMethod([] () {
C c;
c.M([] () -> std::string { // compiler error C2668
return ("txt");
});
});
}
int main() {
}
foo#bar: $ g++ -std=c++0x nested-lambda.cc
Works fine.

Resources