Deploy project without Midas.dll C++ - c++

I am trying to make it so I can deploy a firemonkey project which uses Midas.dll onto another machine without having to copy the DLL over as well. This article explains how to do this with a delphi project by including MidasLib in your uses clause like so:
program Project1;
uses
MidasLib,
Forms,
Unit1 in 'Unit1.pas' {Form1};
I am not very familiar with delphi, but I assume that in C++ I would want to use an #include statement in places of the uses statement. Since MidasLib is a .pas file, I assume I am supposed to include Midas.hpp. However, even though I include Midas.hpp in the file that is using it, I still get an exception saying "Midas.dll not found."
How can I deploy my project without having to copy the Midas.dll file over with it?

You should also link the static library and call the RegisterMidasLib function:
#include <Midas.hpp>
// or use the Project Manager's "Add to Project" option
#pragma comment(lib, "midas.lib")
extern "C" __stdcall DllGetDataSnapClassObject(REFCLSID, REFIID, void **);
void InitMidas()
{
#pragma startup InitMidas 254
RegisterMidasLib(DllGetDataSnapClassObject);
}
Further details here.

Related

Using a c++ builder application with an external dll

I'm trying to use an external dll in my c++ builder application. The dll (let.s call it X.dll) was created with Qt Creator (using MingW 32 bit compiler, tried gcc as well )
and consists of a single functon to keep things simple (besides X.dll, an import library X.a is also created).
The dll header (Dll_lib.h) is basically just
__declspec(dllexport) Dll_method(float *p, int n);
If I create a simple Qt application, add the dll header to it and link it to the dll import library X.a, everythink works as expected.
However, when I try to use the dll in my c++ builder application, I get an "unresolved external _Dll_method referenced from ..." error.
The part of my c++ builder app that references the dll looks like
#include "lib\Dll_lib.h"
#pragma comment(lib, "X.lib")
__declspec(dllimport) Dll_method(float *p, int n);
.....
X.lib was created directly from the dll using the implib tool that comes bundled with c++ builder. I also tried to create X.lib from X.a using coff2omf tool but nothing worked and I always get the same error message.
C++ environments have a habit of name mangling to support overloads, different arguments with the same name, like:
int use(int x, char y); // mangles to something like use__Int__Chr.
int use(double x); // mangles to something like use__Dbl.
This allows the correct one to be linked depending on the arguments.
You may need to wrap it inside extern "C" to get it to not mangle the name, something like:
extern "C" {
__declspec(dllimport) Dll_method(float *p, int n);
}
That's assuming you're creating it without name mangling and using it from something that assumes it is mangled. If it's mangled on both sides, you'll probably have to create and use it with extern "C" since there's no guarantee different compilers will mangle with the same rules.
As an aside, you should be able to examine the object files or DLLs created by your toolchain, to ascertain what the function is called where it's defined and also what it's expected to be by the caller. Under Linux, I'd use something like nm, I'm not sure what the equivalent is for Windows.

Use NetCDF4-C in Unity

this is my first time posting (after lurking for years).
A project I will be tackling is to use NetCDF4 (.nc) files in Unity on Windows. I will be using Unity 5.4.0f3 and Windows 10, and I have developed in Unity before and am familiar with C# and JavaScript, but NetCDF only has C, Java, and Fortran APIs, although there are wrappers in Python, C++, and others (source: https://www.unidata.ucar.edu/publications/factsheets/current/factsheet_netcdf.pdf).
So my specific question is how do I call NetCDF4-C functions (nc_get_vara_float(), nc_open, etc) in C# for use in Unity?
What I've tried so far:
To start, I googled specifically for NetCDF4-C + Unity tutorials/attempts, but did not find anything, so instead I have been looking into the compatibility of calling C functions from C#. I am currently working on a project on Linux with NetCDF4-C and written custom wrapper functions for the netcdf.h functions, so I was hoping I could reuse my code there.
I attempted to follow this SO post (Is it possible to call a C function from C#.Net) but get an error in Unity when trying to Play: "DllNotFoundException: test.so" (my file was named "test.c"). From the comments, it seems Linux uses .so files but Windows uses .dll, and I was not sure how to generate a .dll of a C file.
I looked up another post on that (How to write a DLL file in C?) and downloaded Visual Studio to follow along. While VS was downloading, I looked up how to use GCC to compile (Creating a DLL in GCC or Cygwin?), and used the Bash subsystem ("Bash on Ubuntu on Windows" terminal) but got a handful of errors that indicated the code from the previous link (2nd SO link in this post) were for C++, so I stopped working with GCC.
Once VS finished installing, I went back to trying to use VS to create the .dll, and attempted to combine the solutions from both SO posts (1 and 2) so that I would be able to use the .dll file containing C code in Unity, but to no avail: I get the same error but just with a different extension (and different name on purpose): "DllNotFoundException: Win32Project1.dll".
The code I have is as follows:
test.cs (used in Unity and attaches to a Component):
using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;
public class test : MonoBehaviour {
[DllImport("Win32Project1.dll", EntryPoint="DisplayHelloFromMyDLL")]
public static extern void DisplayHelloFromMyDLL ();
// Use this for initialization
void Start () {
DisplayHelloFromMyDLL();
}
// Update is called once per frame
void Update () {
}
}
Win32Project1.dll (created and built in Visual Studio):
#include <stdio.h>
extern "C"
{
__declspec(dllexport) void DisplayHelloFromMyDLL()
{
printf("Hello DLL.\n");
}
}

Using C++ app in .NET

I am new to using PInvoke with Classic C++ and I asked this question yesterday: Using Windows API functions in .NET
I have now created a very simple C++ program as follows:
#include <iostream>
#include <stdio.h>
#include <string>
extern "C" __declspec(dllexport) int hello()
{
//printf ("Hello World!\n");
return 1;
}
I then compiled the DLL using the following command: g++ -c mydll.cpp
Then created the shared library using the following command: g++ -shared -o mydll.dll mydll.o, then copied mydll.dll to C:\Windows\syswow64.
I then created a new VB.NET project and created the following code:
Imports System.Runtime.InteropServices
Public Class TestPlatformInvoke
<DllImport("mydll.dll", CallingConvention:=CallingConvention.Cdecl)> _
Public Shared Function hello() As Integer
End Function
Public Sub New()
Try
Dim test As Integer = hello() 'Line 6 ex As Exception
'I don't swallow exceptions
MsgBox("test")
Catch ex As Exception
End Try
End Sub
End Class
The application exits after calling hello(). It does not throw an exception.
I am trying to get to grips with how this works. I don't have any commercial experience with c++; only academic experience at university.
Here is an image of Dependancy Walker for mydll.dll.
Declare is VB6 legacy. You should use p/invoke and the DllImport attribute.
<DllImport("mydll.dll", CallingConvention:=CallingConvention.Cdecl)> _
Public Shared Function hello() As Integer
End Function
There are lots of ways that this could fail. Perhaps the DLL is not loading because there's a 32/64 bit mismatch. Also, your calling conventions do not match. Your DLL will be using cdecl but your VB code uses stdcall. The pinvoke above fixes that.
Most seriously your function does not appear to have been exported from the DLL. That's going to make it fail for sure. Use Dependency Walker to determined whether or not your function has been exported. I'm not so familiar with g++ so you'll have to work out how to export your function using the GNU toolchain. But watch out for name decoration and name mangling. You may need to take care with how you export your function so that it is exported with the desired name.
If you use Visual Studio to debug programs and include the DLL in your project (Visual Studio 2012 Express Edition allows including projects of different types in the solution), you may set the "Allow native code debugging" option to automatically switch the debugger from the VB.NET to C++, when you P/Invoke function from the DLL.
Here's a working Proof-of-concept. Simply unzip, open in Visual Studio, build and run. You may compare this program with your project and find the differences, which makes your code failing.
I guess, that you haven't actually exported the function from the DLL. Simply including it in the DLL's code may not be enough: check, which functions are exported from the DLL using the Dependency Walker (other link) program. For example, I had to add folowing declaration:
__declspec(dllexport) int __stdcall Test() { ... }
And additionally create the .def file for the names for exported functions not to be decorated.
Try to modify your DLL source code and change the function declaration to:
extern "C" __declspec(dllexport) int hello()
{
return 1;
}

Having trouble embedding Lua for Windows install into C++ program

This is the first question I have found myself not being able to get to the bottom of using my normal googling/stack overflowing/youtubing routine.
I am trying to compile a minimal Lua program inside of a C++ environment just to ensure my environment is ready to development. The Lua language will be later used for User Interface programming for my C++ game.
First some basic information on my environment:
Windows 7 64-bit
Visual studio 2010
Lua for Windows 5.1 (latest build I could download from google code)
Here is the code I am trying to compile:
// UserInt.cpp : Defines the entry point for the console application.
//
#pragma comment(lib,"lua5.1.dll")
#include "stdafx.h"
#ifndef __LUA_INC_H__
#define __LUA_INC_H__
extern "C"
{
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
}
int _tmain(int argc, _TCHAR* argv[])
{
lua_State * ls = luaL_newstate();
return 0;
}
#endif // __LUA_INC_H__
Here is the Error I am getting:
1>UserInt.obj : error LNK2019: unresolved external symbol _luaL_newstate referenced in function _wmain
1>c:\users\deank\documents\visual studio 2010\Projects\UserInt\Debug\UserInt.exe : fatal error LNK1120: 1 unresolved externals
Things I have tried:
I have read about lua_open()(and several other functions) no longer being used so I tried the newstate function instead. I get the same error. This was more of a sanity check than anything. I am using 5.1 and not 5.2 so I do not think this really matters.
I have also read this thread Cannot link a minimal Lua program but it does not seem to help me because I am not running the same environment as that OP. I am on a simple windows 7 and visual studio environment.
The top pragma comment line was something I saw in yet another thread. I get the same error with or without it.
I have gone into my visual studio C++ directories area and added the lua include to the includes and the lua lib to the libraries.
So it seems like my program is seeing the .h and seeing the symbol. But for some reason it is not getting the .cpp implementation for the functions. This is why I was hoping including that .dll directly would help fix the problem, but it hasn't.
So, I feel like I have exhausted all of my options solving this on my own. I hope someone is able to help me move forward here. Lua looks like an awesome language to script in and I would like to get my environment squared away for development.
I hope it is just some silly error on my part. I believe I have provided as much information as I can. If you need more specifics I will update with info if I can provide it.
Edit1
Tried the solution in this Can't build lua a project with lua in VS2010, library issue suspected
That did not work either.
You'll need to have the library (.LIB) file and add that to VS. Use Project > Properties and go to Linker > Input and add the full .lib filename to the "Additional Dependencies" line. Note that the .LIB is different from the .DLL.
Personally, I prefer adding the source code to my project, over referencing the dynamic link library. The following procedure will let you do as such.
Download the source code ( http://www.lua.org/ftp/ ), uncompress it.
In Visual Studio, choose File > New > Project and choose Visual C++, Win32, "Win32 Console Application".
In your project in Visual Studio, add all the source code, except luac.c. Also delete the main() function out of the file that VS created for you. This is usually given the name of the project you specified with the .cpp file extension. You could just remove this file all-together from the project.
Build and Run.
This is the Lua console

Calling functions in a DLL from C++

I have a solution in VS 2008 with 2 projects in it. One is a DLL written in C++ and the other is a simple C++ console application created from a blank project. I would like know how to call the functions in the DLL from the application.
Assume I am starting with a blank C++ project and that I want to call a function called int IsolatedFunction(int someParam)
How do I call it?
There are many ways to do this but I think one of the easiest options is to link the application to the DLL at link time and then use a definition file to define the symbols to be exported from the DLL.
CAVEAT: The definition file approach works bests for undecorated symbol names. If you want to export decorated symbols then it is probably better to NOT USE the definition file approach.
Here is an simple example on how this is done.
Step 1: Define the function in the export.h file.
int WINAPI IsolatedFunction(const char *title, const char *test);
Step 2: Define the function in the export.cpp file.
#include <windows.h>
int WINAPI IsolatedFunction(const char *title, const char *test)
{
MessageBox(0, title, test, MB_OK);
return 1;
}
Step 3: Define the function as an export in the export.def defintion file.
EXPORTS IsolatedFunction #1
Step 4: Create a DLL project and add the export.cpp and export.def files to this project. Building this project will create an export.dll and an export.lib file.
The following two steps link to the DLL at link time. If you don't want to define the entry points at link time, ignore the next two steps and use the LoadLibrary and GetProcAddress to load the function entry point at runtime.
Step 5: Create a Test application project to use the dll by adding the export.lib file to the project. Copy the export.dll file to ths same location as the Test console executable.
Step 6: Call the IsolatedFunction function from within the Test application as shown below.
#include "stdafx.h"
// get the function prototype of the imported function
#include "../export/export.h"
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
// call the imported function found in the dll
int result = IsolatedFunction("hello", "world");
return 0;
}
Can also export functions from dll and import from the exe, it is more tricky at first but in the end is much easier than calling LoadLibrary/GetProcAddress. See MSDN.
When creating the project with the VS wizard there's a check box in the dll that let you export functions.
Then, in the exe application you only have to #include a header from the dll with the proper definitions, and add the dll project as a dependency to the exe application.
Check this other question if you want to investigate this point further Exporting functions from a DLL with dllexport.
The following are the 5 steps required:
declare the function pointer
Load the library
Get the procedure address
assign it to function pointer
call the function using function pointer
You can find the step by step VC++ IDE screen shot at http://www.softwareandfinance.com/Visual_CPP/DLLDynamicBinding.html
Here is the code snippet:
int main()
{
/***
__declspec(dllimport) bool GetWelcomeMessage(char *buf, int len); // used for static binding
***/
typedef bool (*GW)(char *buf, int len);
HMODULE hModule = LoadLibrary(TEXT("TestServer.DLL"));
GW GetWelcomeMessage = (GW) GetProcAddress(hModule, "GetWelcomeMessage");
char buf[128];
if(GetWelcomeMessage(buf, 128) == true)
std::cout << buf;
return 0;
}
You can either go the LoadLibrary/GetProcAddress route (as Harper mentioned in his answer, here's link to the run-time dynamic linking MSDN sample again) or you can link your console application to the .lib produced from the DLL project and include the hea.h file with the declaration of your function (as described in the load-time dynamic linking MSDN sample)
In both cases, you need to make sure your DLL exports the function you want to call properly. The easiest way to do it is by using __declspec(dllexport) on the function declaration (as shown in the creating a simple dynamic-link library MSDN sample), though you can do it also through the corresponding .def file in your DLL project.
For more information on the topic of DLLs, you should browse through the MSDN About Dynamic-Link Libraries topic.
Might be useful: https://www.codeproject.com/Articles/6299/Step-by-Step-Calling-C-DLLs-from-VC-and-VB-Part-4
For the example above with "GetWelcomeMessage" you might need to specify "__stdcall" in the typedef field before the function name if getting error after calling imported function.
Presuming you're talking about dynamic runtime loading of DLLs, you're looking for LoadLibrary and GetProAddress. There's an example on MSDN.
When the DLL was created an import lib is usually automatically created and you should use that linked in to your program along with header files to call it but if not then you can manually call windows functions like LoadLibrary and GetProcAddress to get it working.