I've got a Windows DLL that I wrote, written in C/C++ (all exported functions are 'C'). The DLL works fine for me in VC++. I've given the DLL to another company who do all their development in VB. They seem to be having a problem linking to the functions. I haven't used VB in ten years and I don't even have it installed. What could be the problem?
I've declared all my public functions as follows:
#define MYDCC_API __declspec(dllexport)
MYDCCL_API unsigned long MYDCC_GetVer( void);
.
.
.
Any ideas?
Finally got back to this today and have it working. The answers put me on the right track but I found this most helpful:
http://www.codeproject.com/KB/DLL/XDllPt2.aspx
Also, I had a few problems passing strings to the DLL functions, I found this helpful:
http://www.flipcode.com/archives/Interfacing_Visual_Basic_And_C.shtml
By using __declspec for export, the function name will get exported mangled, i.e. contain type information to help the C++ compiler resolve overloads.
VB6 cannot handle mangled names. As a workaround, you have to de-mangle the names. The easiest solution is to link the DLL file using an export definition file in VC++. The export definition file is very simple and just contains the name of the DLL and a list of exported functions:
LIBRARY mylibname
EXPORTS
myfirstfunction
secondfunction
Additionally, you have to specify the stdcall calling convention because that's the only calling convention VB6 can handle. There's a project using assembly injection to handle C calls but I guess you don't want to use this difficult and error-prone method.
Try adding __stdcall at the end
#define MYDCC_API __declspec(dllexport) __stdcall
We have some C++ dlls that interact with our old VB6 apps and they all have that at the end.
A VB6 DLL is always a COM dll. I shall describe an example in as few words as possible. Suppose you have a ActiveX DLL project in VB6 with a class called CTest which contains a method as shown below
Public Function vbConcat(ByVal a As String, ByVal b As String) As String
vbConcat = a & b
End Function
and you have set the project name as VBTestLib in VB6 project properties and
you have compiled the project as F:\proj\VB6\ActiveXDLL\VBTestDLL.dll
You need to register the dll using the Windows command
regsvr32 F:\proj\VB6\ActiveXDLL\VBTestDLL.dll
now your C++ code :
#import "F:\proj\VB6\ActiveXDLL\VBTestDLL.dll"
using namespace VBTestLib;
void CDialogTestDlg::OnButton1()
{
HRESULT hresult;
CLSID clsid;
_CTest *t; // a pointer to the CTest object
_bstr_t bstrA = L"hello";
_bstr_t bstrB = L" world";
_bstr_t bstrR;
::CoInitialize(NULL);
hresult=CLSIDFromProgID(OLESTR("VBTestLib.CTest"), &clsid);
hresult= CoCreateInstance(clsid,NULL,CLSCTX_INPROC_SERVER,
__uuidof(_CTest),(LPVOID*) &t);
if(hresult == S_OK)
{
bstrR = t->vbConcat(bstrA , bstrB);
AfxMessageBox((char*)bstrR);
}
}
That's all there is to it, to get started off.
Related
I am working on a project where I am creating a small DLL and then also creating a windows application to use it.
I can not figure out what is going on.
I have a function in the DLL called "startPicadorVisual" which takes one parameter which is a std::string.
In the application which is dependent on the DLL I have the following code in a mostly auto-generated .h file:
typedef void (__stdcall *f_startPicadorVisual)(string s);
namespace PicadorPrototype {
f_startPicadorVisual startPicadorVisual;
Form1(void) {
//Load DLL Funcs
HINSTANCE hGetProcIDDLL = LoadLibrary(L"..\\Debug\\Picador.dll");
if (!hGetProcIDDLL) {
std::cout << "could not load the dynamic library" << std::endl;
throw "Bad Stuff";
}
startPicadorVisual = (f_startPicadorVisual)GetProcAddress(hGetProcIDDLL, "startPicadorVisual");
if (!startPicadorVisual) {
std::cout << "could not locate the function" << std::endl;
throw "More Bad Stuff";
}
When which fails on the second step when I call GetProcAddress.
The functions are defined as follows in my DLL:
void __declspec(dllexport) startPicadorVisual(string fixtureNamet);
PicadorResults __declspec(dllexport) getPicadorReading(string fixtureName);
Can anyone tell me why this isn't working?
GetProcAddress fails if the name you give GetProcAddress doesn't match exactly the name of the function you're calling. By exact I mean everything -- characters that make up the function name, the function name must match casing, etc.
So either your DLL exported a different name and you didn't realize it, or you're not exporting the name at all.
The way you can find out the names of the exported DLL functions easily, you can use the Dependency Walker program found here: http://www.dependencywalker.com/
Also, it isn't a good idea to use C++ objects that allocate dynamic memory such as std::string as parameters. If you do that, your DLL will only work for applications that
Are compiled with the same version of Visual C++ as the DLL
Use the same compiler options when building the application and DLL
All components (DLL and app) must use the DLL version of the C runtime library.
Otherwise, your code would have undefined behavior, more than likely crash, even if you got as far as retrieving the function pointer correctly.
I have DLL file which compiles in Delphi, functions export as __stdcall, and functions description txt file. I havn't got any source code.
And I'll use this DLL in visual studio c++ project. Google says that need use LoadLibrary + GetProcAddress , but GetProcAddress returns NULL if exported function declared as __stdcall, i.e. I can't call function with its name. And others recomended using .def file,
but I don't know what .def file, and what need for generating .def file, if I can use this way on my situation, please describe thoroughly.
QA: How I can call these exported functions?
Here I post my main.cpp file, dll name and function name changed specially.
#include <Windows.h>
#include <tchar.h>
#include <cassert>
#include <cstdio>
int main()
{
//foo(80, 127);
HMODULE hLib;
hLib = LoadLibrary( _T("MyDLL.dll") );
assert(hLib != NULL ); // pass !!
int ( __stdcall *pFoo)(int, int);
(FARPROC &)pFoo = GetProcAddress(hLib, _T("foo") );
if (pFoo== NULL )
{
DWORD errc = GetLastError();
printf("%u\n",errc); // it gets error 127
}else{
printf("success load\n");
}
// pFoo(04,1);
FreeLibrary(hLib);
return 0 ;
}
First of all I suggest that you stop using tchar.h, _T, etc. That was useful when you needed to compile for Windows 98. But it's 2014 and surely you can forget that Windows 98 ever existed. So compile your applications for UNICODE and use L"..." for wide literals.
Of course, GetProcAddress only receives 8 bit text. So your current code is incorrect. You must not use _T("...") for the function name parameter of GetProcAddress. The documentation makes this clear.
Since your code compiles it must be that you are compiling for ANSI or MBCS. And if GetProcAddress returns NULL then clearly the DLL does not export a function with the name that you supply. Some possible reasons:
You did not export the function.
You exported the function but not by that name. Note that whilst Delphi is case insensitive, DLL functions importing/exporting is case sensitive. Perhaps you exported Foo rather than foo.
A trivial DLL that will work with the code in your question:
library MyDLL;
function foo(a, b: Integer): Integer; stdcall;
begin
Result := a + b;
end;
exports
foo;
end.
Note that .def files simple are not pertinent here. Delphi does not use .def files. And the calling convention cannot be relevant either. The name used by Delphi to export a function is not influenced by the calling convention.
I have a dll with exporting function
extern "C" __declspec(dllexport) IDriver * __stdcall GetDriver()
There is a programm which is written on Delphi. It can't see the function GetDriver().
It's double awful because I can not get and modify sources of this program.
What may be the reason of successful loading my dll (according log file) and failed call exporting function? Thank you.
Window 7 x64, Visual Studio 2010, C++ project for x86 target
The most likely explanation is that the function will have been exported with a decorated name. I'd expect it to have been exported with the name GetDriver#0. So you could import it like this:
function GetDriver: IDriver; stdcall; external 'DllName.dll' name 'GetDriver#0';
Use a tool like Dependency Walker to check the exact name used to export the function.
If you cannot modify the Delphi code, then you'll need to make your C++ DLL match. Do that by using a .def file which allows you control over the exported name.
The other problem you will face is that Delphi's ABI for return values differs from that used by most other tools on the Windows platform. Specifically a return value is semantically a var parameter. On the other hand, your C++ compiler will regard the return value as an out parameter. My question on Delphi WideString return values covers exactly this issue.
Because of this, I'd expect the function declaration above to lead to access violations. Instead you should declare the return value to be a Pointer and cast it to an interface reference in your Delphi code. You'll need to double check and make sure that the reference counting is handled appropriately.
Again, if you cannot modify the Delphi code, you need to make the C++ code match. A Delphi interface return value is implemented as an additional var parameter following the other parameters. So, to make your C++ function match, declare it like this:
void __stdcall GetDriver(IDriver* &retVal);
I have acquired a DLL that was created in Visual Basic from a third party vendor(Sensor DLL.dll). This DLL contains functions for talking to a sensor, and I need to call these functions from a Visual C++ program I am writing. The vendor will not provide a header file, and I do not know Visual Basic. If I had a header file this would be a 15 minute project... instead I am still struggling with it a week later. Please Help!
I am told one function (Get_Data) in the DLL is of the form:
Public Function Get_Data(ByVal Handle As String) As String
I have tried several methods for calling this Get_Data function with no success:
Method 1) the DllImport attribute
#using <mscorlib.dll>
using namespace System::Runtime::InteropServices;
namespace Sensor
{
[DllImport("Sensor DLL.dll", EntryPoint = "Get_Data", CharSet = System::Runtime::InteropServices::CharSet::Unicode)]
BSTR Get_Data(BSTR Handle);
}
//then I call the function
Sensor::Get_Data(Handle);
This method seems to be the closest I have gotten to a sloution. It compiles, but gives the following error when it runs:
An unhandled exception of type 'System.EntryPointNotFoundException' occurred
Additional information: Unable to find an entry point named 'Get_Data' in DLL 'Sensor DLL.dll'.
I have tried various datatype combinations/permutations besides BSTR including BSTR*, wchar_t, int, etc. It is possible that I missed one, but each datatype returns the same error.
Method 2) dllimport storage-class attribute
__declspec(dllimport) BSTR Get_Data(BSTR Handle);
//then I call the function
Get_Data(Handle);
This method is confusing to me because I don't specify the DLL I want to import from. I have copied the DLL to the project folder and I have added it to the project manually, so hopefully that means it can be found. When I compile the linker returns the following errors:
error LNK2028: unresolved token (0A00034F) "wchar_t * __cdecl Get_Data(wchar_t *)" (?Get_Data##$$FYAPA_WPA_W#Z) referenced in function "int __cdecl main(void)" (?main##$$HYAHXZ)
error LNK2019: unresolved external symbol "wchar_t * __cdecl Get_Data(wchar_t *)" (?Get_Data##$$FYAPA_WPA_W#Z) referenced in function "int __cdecl main(void)" (?main##$$HYAHXZ)
I suspected maybe this meant I should be using wchar_t or wchar_t* instead of BSTR, but changing to either datatype results in the same error.
Method 3) GetProcAddress
typedef BSTR (*Get_Data_Ptr)(BSTR Handle);
HINSTANCE LoadMe;
LoadMe = LoadLibraryA("Sensor DLL.dll");
if (!LoadMe)
std::cout << "\nDLL failed to load!\n";
Get_Data_Ptr LibMainGet_Data;
LibMainGet_Data = (Get_Data_Ptr)GetProcAddress(LoadMe,"Get_Data");
//then I call the function
LibMainGet_Data(Handle);
This will compile, but gives the following error when run:
An unhandled exception of type 'System.AccessViolationException' occurred
Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
When I mouse over the various parts of this code in debug mode it seems that, like the first method, it was also unable to find the 'Get_Data' entry point in the DLL.
Has anyone called functions from a VB DLL using C++ when you haven't made the DLL yourself and you don't have .idl files, etc? Does anyone have a working example like this you could share?
Thanks!
A VB6 DLL is normally a COM server. You do in fact have the equivalent of a .h file, it has a type library embedded in it. Start this off with Project + Properties, Common Properties, Framework and References. Add New Reference button, Browse tab, select the DLL.
Next, View + Object Browser. You should see the generated Interop library in the list. Open the node to see what is there. You write normal managed code, like gcnew, to create the COM object and call the interface methods. You do need some minimum documentation on the available methods to have a guess at how they should be called.
I believe the missing piece is the calling convention. C++ has its own function calling convention different than VB6 (I assume VB6 since you haven't stated VB.NET explicitly). VB6 uses STDCALL convention whereas C++, depending on the vendor, uses a different calling convention termed __cdecl, which is why you see the __cdecl in the compiler error line for method #2. It assumes your external function is using that calling convention by default. Calling convention is a set of rules describing how functions call one another; specifically about how registers are used, what order parameters are delivered in, how by-value / by-reference is determined, etc.
I would suggest sticking with method #3 since method #1 is for Managed C++ which is not standard C++, and method #2 is unfamiliar to me and looks a bit ambiguous. What you want to try is declaring the function pointer typedef to use STDCALL.
typedef BSTR (__stdcall *Get_Data_Ptr)(BSTR Handle);
In the OLE/COM viewer, in order to view the COM type library in a dll/exe/... you have to open it by using "File->View TypeLib" instead of "File->Bind to File"
It sounds like the DLL isn't actually exporting a function named Get_Data. Open up a command prompt and use dumpbin to get the list of exports of the DLL, e.g.:
dumpbin /exports "Sensor DLL.dll"
(dumpbin.exe is located in VC\bin within your Visual Studio install folder, which istypically something like C:\Program Files\Microsoft Visual Studio 10.0).
Then, replace Get_Data with the actual entry point and see if you have any better luck.
A Visual basic program normally needs a runtime to execute.
If you have a COM object (implemented in VB) use the COM API to communicate with it from C++. You will have to register the COM first. Here is a thread that explains hot to do that: http://forums.devx.com/archive/index.php/t-87059.html
If you use a .NET language, use the method of Hans Passant with a reference that will create an interop dll for you. This is far much easier.
Method 1: Do not do that, if you have a COM object that you want to use from a .NET environment, reference it.
Method 2: You get errors because you lack the the .lib file to properly link to the DLL (statically dynamically linking)
Method 3: Would be a pure dynamic solution but you have to know the exact names of the methods in the DLL. These may vary according to the parameters and calling convention used. This is very similar (actually identical, I would say) to the issue you face with your Method 1 solution. The name of the method is for yure not "Get_Data" but something else. With a tool like the dependency viewer you can have a look at the exported names.
Even Method 3 with the right names is likely to fail because if it is a COM object you will need some environment called Appartment to use the COM objects. You "enter" this appartment by calling CoInitialize. This creates some magical stuff in the TLS (Thread Local Storage) to perform the COM magic. I hope this explains why your tries will be pointless if the DLL you have is happening to be a COM component, what is quite likely according to the ATL like naming we can see.
EDIT:
I forgot to say that you can also easily see what is inside the dll if it is a COM with the OLE/COM Viewer (normally if you have a compiler you will have such a tool around).
I've compiled a DLL in Visual Studio (the source code is in C++, which I barely understand). Here's a piece of Scraper.h:
struct SWin
{
char title[512];
HWND hwnd;
};
SCRAPER_API bool ScraperGetWinList(SWin winList[100]);
Now I'm trying to use the above function in my Delphi application:
type
tWin = record
title: String;
hwnd: HWND;
end;
function ScraperGetWinList(var WinList: Array of tWin): Boolean; external 'Scraper.dll';
var
myWinList: Array [1..100] of tWin;
procedure TMainForm.GetWinListButtonClick(Sender: TObject);
begin
ScraperGetWinList(myWinList);
...
The project doesn't compile, and I get the following message: The procedure entry point ScraperGetWinList could not be located in the dynamic link library: Scraper.dll.
What am I doing wrong?
From my Linux experience, I'd say that you've encountered so-called "name-mangling" issue. The entry point of your procedure is not called "ScraperGetWinList", but something like "_ZN18ScraperGetWinListEpN4SWin".
The thing is that, Unlike in C, in C++ language the name of entry point is not the same as the function name. No wonder: assume, you have a set of overloaded functions; they should have different entry points in your DLL. That's where name mangling comes into play.
The most common solution to this problem is to define interface of your library in such a way that it will use C calling convention. No name mangling will happen with the interface functions then.
Note that you don't have to write the whole library in C, you only should declare functions for them to emit C-like entry points.
Usually it's written like this:
extern "C" {
SCRAPER_API bool ScraperGetWinList(SWin winList[100]);
// More functions
}
Recompile your library and use it in Delphi without problems.
Note, that you should also adjust calling conventions (stdcall or cdecl) for them to match in your C++ header and Delphi code. However, that's best explained in another question.
Name mangling is most likely the problem. Name mangling is usually done is C++ code,
and when writing a DLL in C++ that should be used by code in an other langauge,
you should use the Extern "C" construction as Pavel Shved already suggested.
When using DLLs, especially when writtin in other languages, you should also keep
an eye on calling conventions. I suggest that you specify in both delphi and c++ to use the stdcall calling convenstion. This is the calling convention also used by the windows api, so it guarantees the best interoperatability between different compilers.
This would mean
extern "C" {
SCRAPER_API __stdcall bool ScraperGetWinList(SWin winList[100]);
}
and
function ScraperGetWinList(var WinList: Array of tWin): Boolean; external 'Scraper.dll';
But that's not all, the stdcall calling convention has an impact on the name mangling, and it would turn out to be something like _ScraperGetWinList#4 (Where 4 is the size of the parameter, where an array would have a pointer to the first element, so 4 bytes)
To confirm the correct symbols to use, I suggest Dependency Walker
( http://www.dependencywalker.com/ ) this program shows that exactly the function names are exported by the dll. Having confirmed the name to be '_ScraperGetWinList#4' then you add this in delpgi like this:
function ScraperGetWinList(var WinList: Array of tWin): Boolean; external 'Scraper.dll' name '_ScraperGetWinList#4';
Have you actually exported the entry point function in the c++ code? This really stumped me the first time I compiled a C++ dll in Visual Studio for use in a dotnet app.
For example, I needed to expose a print driver in unmanaged code so some other developers could access it in VB.net. This is what I did.
In foo.cpp:
extern "c" {
___declspec(dllexport) bool FooBar()
{
// Call some code on my cpp objects to implement foobar
}
}
Then in a file called foo.def:
LIBRARY "mylib"
EXPORTS
FooBar
AnyOtherFunctionsItExports
This is how I got it to work. I might not be doing things the best possiable way. I am a little light on C++ experience and also mainly don't work on windows.