VC++: Using DLLs as "subprograms" - visual-c++

So I just began to try my hand at emulation after years of putting it off and not knowing where to start and I have managed to successfully write my first emulator! Now I am organizing my code in so that I can reuse the code to emulate other systems. I've been toying with the idea of having a shared frontend "platform handler" of sorts that I will compile as my executable whereas I will compile my emulated system code into dlls that the platform handler will use to identify what is available and instantiate from. This would allow me to separate my code into different projects and to leave the option open of using a bulkier front-end with more features or a streamlined "game only" and to share the same dlls between them rather than make two different solutions.
I know how to compile dlls vs executables but I don't know how to link the executable to the custom dll in such a way that I can instantiate a class from it. I'm not even sure what I'm trying to do is technically possible. Do the dll classes need to be static? I've never coded anything like this before or even done much with custom dlls so any help or ideas would be appreciated. I'm using Visual C++ 2010 by the way. Thanks in advance for any advice anyone may have.

You don't really have to do much different. Just export your classes from the dll like you do for functions. In your app, include the header and link to the generated lib like you usually do. See this page: http://msdn.microsoft.com/en-us/library/81h27t8c%28v=vs.80%29.aspx
Example.h
#ifdef DLL_EXPORT
#define EXPORT_API __declspec(dllexport)
#else
#define EXPORT_API __declspec(dllimport)
#endif
class EXPORT_API Example
{
public:
Example();
~Example();
int SomeMethod();
};
int EXPORT_API ExampleFuncion();
Example.cpp
#include "Example.h"
Example::Example()
{
// construct stuff
}
Example::~Example()
{
// destruct stuff
}
int Example::SomeMethod()
{
// do stuff
return 0;
}
int EXPORT_API ExampleFunction()
{
return 0;
}
In your dll project, define DLL_EXPORT and build. You will get a .lib and .dll output. In your main project where you will be using the dll you do not have to do anything except include the header and link against the .lib. Do not define the DLL_EXPORT symbol in your main project and be sure the .dll is somewhere your application can find it.
If you really want to get clever, this problem is screaming for the factory design pattern. If you design your interface well enough, you can have your dlls register their implementation with your application when they are loaded. You can extend forever without even rebuilding your main executable.

Related

How to use a pre-compiled .so file in another android app?

I wonder why there is no proper answer to this question, I searched for couple of hours but no good answer.
So, we work on a team in which my friend wrote a C library and compiled it as a .so file (it's called ttplib.so)(assume I don't have access to it's C code). Now I have to use that .so file in my android application. But I don't know how to load the library and how to use its methods. I have good documentation of it.
That would be great if you can tell me how to create the Android.mk file too.
Do I have to use dlopen?
Put ttplib.so in the new project's libs/armeabi or libs/armeabi-v7a folder depending what it was compiled with.
Somewhere in your new app (before interacting with the library) add this line of code
System.loadLibrary( "ttplib" );
Now that it's loaded in memory, you'll need to interact with it using JNI. You'll have to go back to the C code to export some JNI functions:
JNIEXPORT jint JNICALL Java_com_example_package_MyClass_methodName( JNIEnv* env, jobject jthis, jfloat value )
{
return 5;
}
Then you'll need to add ClassName.java in your new project:
package com.example.package;
public class MyClass
{
private native int methodName( float value );
private void someJavaMethod()
{
int i = methodName( 65.33f );
}
}
That's it, in a nutshell.

Use a supplied dll in Visual C++ project

I just bought a device that comes with a dll file. I want to use Visual C++ to program the device. How do I load the .dll file into my project?
A DLL is a library file that contains compiled program logic, just like an EXE. You can't execute it alone, but like an EXE file you can't just 'load' it into your project either.
You will need to use functions like Load Library to load the library, and then GetProcAddress to find a function you want to call.
Edit:
After you clarified your question in the comments you are trying to write a windows program instead of a program you run on your device.
I wrote some sample code to show you how to start:
#include <windows.h> // This is a windows header file. The functions I mentioned above are declared here
#include "mpusbapi.h" // This is the header file supplied. It declares the function prototypes that are defined in the DLL
int main(int argc, char* argv)
{
// Try to load the library
HMODULE mpbusDLL = NULL;
mpbusDLL = LoadLibrary(L"mpusbapi.dll");
if (mpbusDLL != NULL) {
// If the library could be loaded, then load the functions using GetProcAddress()
// Load the function 'MPUSBOpen' from the DLL
MPUSBOpen = (HANDLE(*)(DWORD, PCHAR, PCHAR, DWORD, DWORD)) GetProcAddress(mpbusDLL, "_MPUSBOpen");
...
MPUSBOpen(...);
}
}
This C code will load your libary and then attempt to load the function MPUSBOpen, which is implemented in your DLL.
You will need to load the other functions defined in your header file the same way (at least if you want to use them).

call unmanaged C++ code from C# using pinvoke

I have a unmanaged C++ dll for which I do not have access to code but have all methods declarations for.
Lets for simplicity say that .h looks like this:
#include <iostream>
#ifndef NUMERIC_LIBRARY
#define NUMERIC_LIBRARY
class Numeric
{
public:
Numeric();
int Add(int a, int b);
~Numeric();
};
#endif
and method implementation in .cpp file
int Numeric::Add(int a, int b)
{
return (a + b);
}
I simply want to call the add function from C++ in my C# code:
namespace UnmanagedTester
{
class Program
{
[DllImport(#"C:\CPP and CSharp Project\UnmanagedNumeric\Debug\numeric.dll", EntryPoint = "Add")]
public static extern int Add(int a, int b);
static void Main(string[] args)
{
int sum = Add(2, 3);
Console.WriteLine(sum);
}
}
}
After trying to execute I have the following error:
Unable to find an entry point named 'Add' in DLL 'C:\CPP and CSharp Project\UnmanagedNumeric\Debug\numeric.dll'.
I CAN NOT change C++ code. Have no idea what is going wrong.
Appreciate your help.
Using PInvoke you can only call global functions exported from Dll. To use exported C++ classes, you need to write C++/CLI wrapper. This is C++/CLI Class Library project, which exposes pure .NET interface, internally it is linked to unmanaged C++ Dll, instantiates a class from this Dll and calls its methods.
Edit: you can start from this: http://www.codeproject.com/KB/mcpp/quickcppcli.aspx#A8
If you need to create a wrapper, take a look at swig.org. It will generate one for most high level language like C#.
I just came across this program a few minutes ago while working the same problem that you are.
To use a class from native C++ from C# you need a C++/CLi wrapper in between, as mentioned by by previous answers. To actually do that, it is not very straight forward. Here is I link that tell you how to do it at a high level: C++/CLI wrapper for native C++ to use as reference in C#.
If you are quite new to this (like me), you might stumble on 1) -- the linking part. To solve that, you can see how I did here (see my question portion): Link error linking from managed to unmanaged C++ despite linking to .lib file with exported symbols

Can you force MonoTouch to include an unreferenced assembly in its static compilation?

I have a MonoTouch app that dynamically instantiates a class (using Type.GetType()) at runtime. The class is in an assembly that is not referenced anywhere else in the app, so the MonoTouch static compiler thinks that the assembly isn't used and ignores the assembly when it compiles the app. If I add a reference to the class in the app, then the compiler includes the assembly and the call to Type.GetType() works fine:
MyAssembly a;
I would prefer to just tell the compiler to always include all the assemblies listed in the project's "References" when it compiles the app. Is this possible?
Thanks,
-Tom B.
You will have to change your project's Linker behavior from "Link all assemblies" to "Link SDK assemblies only".
The other solution, if you have the project code that assembly was created with, is to mark the class you want to use with the PreserveAttribute.
Were you able to figure this out yet? If not, I had a similar problem: Is there a way to force MonoDevelop to build/load an assembly?
As I understand it, that's just how the C# compiler works. I was able to get around this by adding a custom pre-build step that scripts a class into the referencing assembly that includes dummy references to the unreferenced assemblies, like so:
using System;
namespace MyNamespace
{
public static class Referencer
{
Type t;
//These lines are scripted one per class in the unreferenced assemblies
//You should only need one per assembly, but I don't think more hurts.
t = typeof(Namespace1.Class1);
t = typeof(Namespace2.Class2);
...
t = typeof(NamespaceN.ClassN);
}
}

Will the linker compare the access level when finding a member function at linking time?

Accidently, I encounter a linking error.
The program is somewhat like this:
//a.h
class A
{
int a;
#ifdef AAA
public:
#endif
int getA();
}
//a.cpp
include "a.h"
int A::getA()
{
return a;
}
//test.cpp
#include "a.h"
int main()
{
A a;
a.getA();
return 0;
}
These three files are in two project, a.h and a.cpp in a project A in which the AAA macro is undefined, test.cpp in a project Test in which AAA macro is defined. And project Test denpends on project A.
Then I encounter a link error. I did this test on visual studio 2008.
So my question is this:"Will the link compare the access level when finding a member function symbol at linking time?"
In my previous opinion, the access level only take effect in compilation. But in this case,
it seems that the access level may also make effect in linking time.
The linker is innocent. C++ compilers mangel names and incorporates things as access modifiers, overloads (i.e. return and argument types), template(? not quite sure) etc... in the final to produce something unambigious that also forms whatever the linker considers a valid identifier (at least [a-zA-Z_][a-zA-Z0-9_]*, as C requires no mangling). The linker only sees that mangled name, and it can't report anything except "you call this function but it's not defined anywhere". public A::getA() a different name as private A::getA().
The solution? Don't use the preprocessor for such batshit things. Or convince the VS developers to intercept such error messages and translate them into something more meanignful (but since they didn't in the past and sane code rarely encounters this problem, that's unlikely).

Resources