tcpclient C3145 - dll

I'm currently using Visual Studio C++ to generate .dll in order to transmit data between two programs: essentially, one program notifies the other when an event occurs. I'm trying to do this via a TcP client socket.
my header file goes something like this:
#include <string>
using namespace std;
extern "C"
{
__declspec (dllexport) bool trackerConnect( char* ipAddress, int port );
__declspec (dllexport) void sendEvent ( char* ev);
__declspec (dllexport) void disconnect();
}
My .cpp file looks something like this
#define WIN32_LEAN_AND_MEAN
#include "logEvents.h"
#using "system.dll"
using namespace System;
using namespace System::Net;
using namespace System::Net::Sockets;
using namespace System::Text;
TcpClient^ logClient;
NetworkStream^ logStream;
bool trackerConnect( char* ipAddress, int port )
{
/*Connects to server, gets stream, and returns whether the connection was
successful or not*/
}
void sendEvent ( char* ev )
{
/*Converts ev into a Byte array and sends it to the server to notify it
that an event has occurred*/
}
void disconnect ()
{
//closes the connection with the server
}
Given that all three functions need access to the TcPClient, I declared it as a global variable. However, when I compile, I get error C3145: global or static variable may not have managed type. If I can't declare the TcPClient as a global variable, how am I supposed to use it in the three functions?

Related

QTcpSocket does not emit connected()

I'm using QT5 and starting out with a basic Server/Client setup. I'm looking at going single threaded for both apps as there is no heavy processing on network data. Now, from everything I've read and researched here, when using asynchronous approach, you don't use waitForXXXX() otherwise it messes up all the signals and slots. The problem - On the client end, the connected() signal is either never emitted or never processed, even though the server consoles tells me that a new client has connected. I've been working on the same issue for 2 weeks now and couldn't find the exact same issue anywhere. I've stripped back both apps to the minimum and still no luck - also stripped out the UI part now - I just want see the console working. I have also tried switching to public slots and changing the signal/slot connection type and still have the same problem.
If you require code from the server, please let me know, but here is the basics of the client:
main.cpp
#include "QGameSocket.h"
#include <QtWidgets/QApplication>
#include <windows.h>
int main(int argc, char *argv[])
{
AllocConsole();
freopen( "conin$", "r", stdin );
freopen( "conout$", "w", stdout );
freopen( "conout$", "w", stderr );
QApplication a( argc, argv );
QGameSocket* pSocket = new QGameSocket();
return a.exec();
}
QGameSocket.h
#ifndef _QGAMESOCKET_H
#define _QGAMESOCKET_H
#include <QtNetwork/qtcpsocket.h>
#pragma comment ( lib, "Qt5Network.lib" )
class QGameSocket: public QObject
{
Q_OBJECT
public:
explicit QGameSocket( QObject* pParent = 0 );
~QGameSocket();
private slots:
void __OnConnected();
void __OnReadyRead();
private:
QTcpSocket* m_pSocket;
};
#endif
QGameSocket.cpp
#include "QGameSocket.h"
#include <qdatastream.h>
QGameSocket::QGameSocket( QObject* pParent ) :
QObject( pParent )
{
m_pSocket = new QTcpSocket();
connect( m_pSocket, SIGNAL( connected() ), this, SLOT( __OnConnected() ) );
connect( m_pSocket, SIGNAL( readyRead() ), this, SLOT( __OnReadyRead() ) );
const QString strHost = "127.0.0.1";
qDebug() << "Connecting to host ...";
m_pSocket->connectToHost( strHost, 27015 );
}
QGameSocket::~QGameSocket()
{
m_pSocket->deleteLater();
}
void QGameSocket::__OnConnected()
{
qDebug() << "Successfully connected to host!";
}
void QGameSocket::__OnReadyRead()
{
//handle messages
}
Any help would be much appreciated, thank you!
I finally figured it out - I was using the release network library, not the debug library.
I changed:
#pragma comment ( lib, "Qt5Network.lib" )
to
#pragma comment ( lib, "Qt5Networkd.lib" )

How do we add an event in C++/WinRt project?

I am currently work on a C++/WinRt which connects(Sender) to one of the available devices(Client) around a specific region using WifiDirect. When the device wants to connect, it sends a connection request to the sender. The sender needs to detect the connection request sent by the client and connect to the client. For this I need to add an event - (On Connection requested). As soon as I add it should execute the code of OnConnectionRequested.
#include "pch.h"
#include <winrt/Windows.Foundation.Collections.h>
#include "winrt/Windows.Devices.WiFiDirect.h"
#pragma once
using namespace winrt;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::Devices::WiFiDirect;
using namespace Windows::Storage::Streams;
using namespace winrt::Windows::Devices::WiFiDirect;
using namespace winrt::Windows::Devices::Enumeration;
enum class NotifyType
{
StatusMessage,
ErrorMessage
};
enum class CallbackContext
{
Any,
Same
};
class st
{
public:
void OnConnectionRequested(WiFiDirectConnectionListener sender,
WiFiDirectConnectionRequestedEventArgsconnection EventArgs)
{
WiFiDirectConnectionRequest connectionRequest = connectionEventArgs.GetConnectionRequest();
printf("Connection request received from ", connectionRequest.DeviceInformation().Name(), "Connection Request");
printf("Connecting to ", connectionRequest.DeviceInformation().Name(), NotifyType::StatusMessage);
}
void start()
{
Windows::Devices::WiFiDirect::WiFiDirectAdvertisementPublisher _publisher;
Windows::Devices::WiFiDirect::WiFiDirectConnectionListener _listener;
winrt::event_token _connectionRequestedToken;
try
{
_connectionRequestedToken = _listener.ConnectionRequested({this, &st::OnConnectionRequested});
_publisher.Start();
printf("Advertisement started, waiting for StatusChangedcallback...", NotifyType::StatusMessage);
}
catch (...)
{
printf("Error starting Advertisement: ", NotifyType::ErrorMessage);
}
getchar();
}
};
int main()
{
st s;
s.start();
}
Is this the right way to add an event in C++/WinRt :
_connectionRequestedToken = _listener.ConnectionRequested({this, &st::OnConnectionRequested});
The errors are :
LNK1120 1 unresolved externals - error in Winrt.exe file
LNK2019
unresolved external symbol "public: struct winrt::hstring __thiscall
winrt::impl::consume_Windows_Devices_Enumeration_IDeviceInformation::Name(void)const
"
(?Name#?$consume_Windows_Devices_Enumeration_IDeviceInformation#UIDeviceInformation#Enumeration#Devices#Windows#winrt###impl#winrt##QBE?AUhstring#3#XZ)
referenced in function "public: void __thiscall
st::OnConnectionRequested(struct
winrt::Windows::Devices::WiFiDirect::WiFiDirectConnectionListener,struct
winrt::Windows::Devices::WiFiDirect::WiFiDirectConnectionRequestedEventArgs)"
(?OnConnectionRequested#st##QAEXUWiFiDirectConnectionListener#WiFiDirect#Devices#Windows#winrt##UWiFiDirectConnectionRequestedEventArgs#3456##Z) - error in Program.obj 1
What changes should I make at this line to clear the error? What does the error actually mean ? Or is there any other way to add an event in C++/WinRt project?
You are missing an #include directive:
#include <winrt/Windows.Devices.Enumeration.h>
See Why is the linker giving me a "LNK2019: Unresolved external symbol" error?:
If the unresolved symbol is an API from the Windows namespace headers for the C++/WinRT projection (in the winrt namespace), then the API is forward-declared in a header that you've included, but its definition is in a header that you haven't yet included. Include the header named for the API's namespace, and rebuild. For more info, see C++/WinRT projection headers.
For general instructions on how to handle events see Handle events by using delegates in C++/WinRT.
Capturing this (raw pointer) into the delegate might be dangerous, too. This breaks the link between object lifetime and visibility, and puts the burden of lifetime management on you. See Safely accessing the this pointer with an event-handling delegate for safer, more manageable alternatives.

Assembly.GetExecutingAssembly() not working in embedded mono?

I'm trying to embed mono in a c++ executable, and mono crashes on Assembly.GetExecutingAssembly. Any idea of what I missed ?
EDIT : using mono 3.0.3
EmbeddedMonoTest.cpp :
// EmbeddedMonoTest.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <mono/metadata/debug-helpers.h>
#include <mono/metadata/exception.h>
#include <mono/jit/jit.h>
#include <mono/metadata/assembly.h>
int _tmain(int argc, _TCHAR* argv[])
{
MonoDomain* domain = mono_jit_init_version ("ClassLibrary1", "v4.0.30319");
MonoAssembly* _assembly_fbmonoengine = mono_domain_assembly_open (domain, "ClassLibrary1.dll");
MonoImage* _image_fbmonoengine = mono_assembly_get_image (_assembly_fbmonoengine);
MonoClass* klass = mono_class_from_name(_image_fbmonoengine, "ClassLibrary1", "Class1");
MonoMethod* test = mono_class_get_method_from_name(klass, "Test" , 0);
mono_runtime_invoke(test, NULL, NULL, NULL);
return 0;
}
Class1.cs :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace ClassLibrary1
{
public class Class1
{
public static void Test()
{
Assembly.GetExecutingAssembly();
}
}
}
The error :
Unhandled exception at 0x65ad2148 in EmbeddedMonoTest.exe: 0xC0000005: Access violation reading location 0x`00000008.
You're not executing any assembly in your program, so ExecutingAssembly in that context has no meaning (a better error is needed, though).
You need to provide the usual static Main() entry point in the assembly and execute it with mono_runtime_exec_main().

How to use P\Invoke in VB.Net

I have number of C++ API's and I want to access them using P\Invoke in VB.Net.Following are the C wrapper written for some of the API's.Can anybody tell me how to use P\Invoke to access these methods in VB.Net.
In wrapper.h:
typedef void * VERIFY_HANDLE;
extern VERIFY_HANDLE Verify_Create();
extern void VERIFY_SetVerified(VERIFY_HANDLE, bool);
extern bool VERIFY_GetVerified(VERIFY_HANDLE);
/* etc, etc */
In wrapper.c:
#include "wrapper.h"
#include "Verify.h"
VERIFY_HANDLE Verify_Create() { return (VERIFY_HANDLE) new Verify(); }
void SetVerified(VERIFY_HANDLE h, bool b) { ((Verify *)h)->SetVerified(b); }
bool GetVerified(VERIFY_HANDLE h) { return ((Verify *)h)->GetVerified(); }
The free P/Invoke Interop Assistant can create Vb.Net P/Invoke code automatically from that C header file.

How do I use WTL in a DLL?

I'm trying to use WTL within an in-process COM server DLL (an IE BHO), but am struggling with _Module.
My DLL needs CMyModule derived from CAtlDllModuleT<>:
class CMyModule : public CAtlDllModuleT< CMyModule >
{
public:
DECLARE_LIBID(LIBID_MyLib)
DECLARE_REGISTRY_APPID_RESOURCEID(IDR_MYPROJ, "{...}")
};
CMyModule _Module;
extern "C" BOOL WINAPI DllMain(...)
{
hInstance;
return _Module.DllMain(dwReason, lpReserved);
}
...
STDAPI DllUnregisterServer(void)
{
return _Module.DllUnregisterServer();
}
But this conflicts with most WTL examples, which require something like this within stdafx.h:
extern CAppModule _Module; // WTL version of CComModule
No matter which way I do it, I (unsurprisingly) get compile errors. CMyModule derived from CAppModule borks on _Module.DllUnregisterServer(), etc. CMyModule derived from CAtlDllModuleT<> borks on code like _Module.GetMessageLoop().
Any good references on how WTL is supposed to work within a DLL? Google finds lots of questions, with few answers.
I have a project that uses WTL in a DLL. I looked at how my headers are set up and it looks like I hacked around this same problem...
I have my module set up like your sample code inheriting from CAtlDllModuleT<> except the name of the global module variable is _AtlModule rather than _Module. For example:
class CMyModule : public CAtlDllModuleT< CMyModule >
{
public:
DECLARE_LIBID(LIBID_MyLib)
DECLARE_REGISTRY_APPID_RESOURCEID(IDR_MYPROJ, "{...}")
};
CMyModule _AtlModule;
So, all of the DllMain.cpp entry points use _AtlModule. Then in the stdafx.h file it looks like this:
// WTL includes
#define _Module (*_pModule)
#include <atlapp.h>
#include <atlctrls.h>
#include <atldlgs.h>
#undef _Module
That _pModule thing is defined in atlbase.h like:
__declspec(selectany) CComModule* _pModule = NULL;
There must be a better way, but this does work.
Have you considered the option of multiple inheritance? Try inheriting from both CAtlDllModule and CAppModule since you need both.
I use WTL in an Office add-in; the following works for me. (At the bottom of stdafx.h)
class DECLSPEC_UUID("XXXX-...") MyLib;
using namespace ATL;
/*
* Application module
*/
class CAddInModule : public CAtlDllModuleT< CAddInModule >
{
public:
CAddInModule() : m_hInstance(NULL)
{
}
DECLARE_LIBID(__uuidof(MyLib))
HINSTANCE GetResourceInstance()
{
return m_hInstance;
}
void SetResourceInstance(HINSTANCE hInstance)
{
m_hInstance = hInstance;
}
private:
HINSTANCE m_hInstance;
};
extern CAddInModule _AtlModule;
And then the DLL main use _AtlModule:
// DLL Entry Point
extern "C" BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved)
{
_AtlModule.SetResourceInstance(hInstance);
return _AtlModule.DllMain(dwReason, lpReserved);
}
// Used to determine whether the DLL can be unloaded by OLE
STDAPI DllCanUnloadNow(void)
{
return _AtlModule.DllCanUnloadNow();
}
// Returns a class factory to create an object of the requested type
STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID* ppv)
{
return _AtlModule.DllGetClassObject(rclsid, riid, ppv);
}
// DllRegisterServer - Adds entries to the system registry
STDAPI DllRegisterServer(void)
{
// registers object, typelib and all interfaces in typelib
HRESULT hr = _AtlModule.DllRegisterServer();
return hr;
}
// DllUnregisterServer - Removes entries from the system registry
STDAPI DllUnregisterServer(void)
{
HRESULT hr = _AtlModule.DllUnregisterServer();
return hr;
}