A simple DLL using VS2010 MFC + a test app - c++

I am trying to build a very simple DLL file which supports MFC.
I use VS2010.
All the examples I found on the net shows how to export class function members.
But my client, at the end, should be a C program. Meaning, it doesn't know to use classes and objects.
I just need to export some simple functions for it.
What I did until now is to put the following on my dll cpp file:
extern "C" __declspec(dllexport) CString SayHello (CString strName){
return theApp.SayHello(strName);
}
and on the app class I wrote:
CString CMyDLLApp::SayHello(CString strName){
return (CString)"Hello " + strName;
}
I created a simple dialog based app, which was suppose to use this function like this
CString strResult = SayHello(m_edit);
After I included the DLL h file at the top of the file:
#include "..\MyDll\MyDll.h"
But the compiler says : error C3861: 'SayHello': identifier not found
Can you please guide me how to do it? Don't offer me to not to use MFC on my DLL because I want to use the DB classes of it.
Also, how to tests it? I don't care if the test program itself is MFC based as well.

Try this declaration in your app to get rid of the compiler error:
extern "C" __declspec(dllimport) CString SayHello (CString strName);
But you cannot get theApp directly from within the DLL. Add another DLL function to pass a pointer to theApp to the DLL.

Related

Standard method for creating dll in c++ and calling in delphi

I am looking for the correct method to create a DLL in C++ and call it in Delphi. I use CodeBlocks for the DLL and Delphi RAD Studio 10.2.
My C++ header and source code for building the DLL as described in How to create dll in C++ for using in C# is as follows:
Main.h:
#ifndef MATH_HPP
#define MATH_HPP
extern "C"
{
__declspec(dllexport) int __stdcall math_add(int a, int b);
}
#endif
Main.Cpp :
#include "main.h"
int __declspec(dllexport) __stdcall math_add(int a, int b)
{
return a + b;
}
This code in CodeBlocks builds math_dll.dll without any error.
Calling the DLL in Delphi:
function math_add(X, Y: Integer): Integer; stdcall; external 'math_dll.dll' name 'math_add';
But when I run Delphi and call this function, I have the following error:
"the procedure entry point math_add could not be located in the dynamic link library math_dll.dll"
Which part of my code is wrong?
The default name mangling for the __stdcall calling convention is _<name>#<bytes_in_arguments>. So your DLL function is most likely being exported as '_math_add#8' instead of as 'math_add' like you are expecting. Use a tool like PEDUMP to verify that.
You can use a .DEF file when compiling the DLL to change the exported name, or you can update your Delphi function declaration to use the correct exported name for the name attribute.

LoadLibrary fails with error 203: The system could not find the environment option that was entered

I created a c# class library. I want to load this .dll in my win32 console application, because I have exported one function from the c# class library to unmanaged code and I don't know of any other way to call that function now.
But LoadLibraryA is giving me that error, what can it mean? Googling didn't help me at all.
Used this to export the function to unmanaged:
https://sites.google.com/site/robertgiesecke/Home/uploads/unmanagedexports#TOC-C-:
EDIT: Here is the code, sorry I didn't include it at first because it's as barebones as it gets:
using System;
using RGiesecke.DllExport;
using System.Runtime.InteropServices;
namespace ManagedLibrary
{
public class Test
{
[DllExport(CallingConvention = CallingConvention.Cdecl)]
public static void test()
{
Console.WriteLine("HI");
}
}
}
Looks like the unmanaged exports nuget tool doesn't work for me, the .dll loading errors were mostly obscure and unrelated as it seems (although I did switch to my home computer now)
After I have manually added the exports IL statement as described here:How do you export a method in a CIL DLL so that a native program can call it? I was able to call the C# code just fine.

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;
}

Can't find DLL entry point

I have been trying to call a DLL function in my VBA project but I keep getting this error message:
Run-time error '453': Can't find DLL entry point "CheckStatus" in "Power.dll"
Here is the definition for the DLL in the C++ file:
#define CLASS_DECLSPEC extern "C" __declspec(dllexport)
CLASS_DECLSPEC int __stdcall CheckStatus();
And here is how I'm trying to declare it and call it in VBA:
Public Declare Function CheckStatus Lib "Power.DLL" () As Long
Dim test As Long
test = CheckStatus
And then when I run it received the aforementioned error message.
Does anyone know how to fix this? Thanks.
This has to do with name mangling (even with extern "C").
Look at what export is really in the DLL, a guess would be either _CheckStatus or _CheckStatus#0.
To force the name to be as-is, make a .def file in your project with the content:
EXPORTS
CheckStatus=CheckStatus
using this MSDN article, I would try this method of declaring the function:
Public Declare Function CheckStatus Lib "Power.DLL" Alias "_CheckStatus#0" () As Long

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.