How can I use the functions in a DLL in C without a LIB file to go with it? I know all of the function prototypes and their names.
Yes you can. You should use the GetProcAddress function, to call the function directly in the DLL, without involving the LIB
Processes explicitly linking to a DLL call GetProcAddress to obtain
the address of an exported function in the DLL. You use the returned
function pointer to call the DLL function.
To quote the Example from the above link:
typedef UINT (CALLBACK* LPFNDLLFUNC1)(DWORD,UINT);
...
HINSTANCE hDLL; // Handle to DLL
LPFNDLLFUNC1 lpfnDllFunc1; // Function pointer
DWORD dwParam1;
UINT uParam2, uReturnVal;
hDLL = LoadLibrary("MyDLL");
if (hDLL != NULL)
{
lpfnDllFunc1 = (LPFNDLLFUNC1)GetProcAddress(hDLL,
"DLLFunc1");
if (!lpfnDllFunc1)
{
// handle the error
FreeLibrary(hDLL);
return SOME_ERROR_CODE;
}
else
{
// call the function
uReturnVal = lpfnDllFunc1(dwParam1, uParam2);
}
}
You can use LoadLibrary() and GetProcAddress() as described in the answer by DarkXphenomenon. Or, another alternative is to create your own import library for the DLL by creating a .def file then running that through the LIB command to generate an import library. Additional details here:
http://support.microsoft.com/kb/131313
Related
I am using (Unicode) Inno Setup 6.0.5 on Windows 10 64-bit.
The exported symbol, I want to use has the signature:
typedef int(__stdcall *GetDirVST2x86) (LPWSTR lpString1);
The Inno Setup [Code] section has its declaration as:
function GetDirVST2x86(var lpString1: String): Integer;
external 'GetDirVST2x86#files:R2RINNO.DLL stdcall setuponly';
where, lpString1 will contain a pointer to the wide-string after the function returns and R2RINNO.DLL is a 32-bit DLL.
Now my problem is, if I compile and run this setup, a read access violation occurs right when I try to retrieve the value. I get the correct result when I execute this same function from a C program. Removing the var from the prototype declaration in Inno script fetches an empty (or possibly) empty or blank string, so that doesn't help either.
I don't have the source for the DLL I wish to use, and I figured out the signature from IDA. The scripting engine Inno Setup seems hopelessly inadequate as it doesn't support pointers at all.
One interesting thing I observed was if I changed the type of lpString1 to Cardinal or Integer and used IntToStr to fetch the string I got the value of the directory in which the setup was getting created.
Here's a working C code:
#include <windows.h>
#include <stdio.h>
#define _UNICODE
#define UNICODE
typedef int(WINAPI *GetDirVST2x86) (LPWSTR );
int main() {
HMODULE hModule = LoadLibrary("R2RINNO.DLL");
if (NULL != hModule) {
GetDirVST2x86 pGetDirVST2x86 = (GetDirVST2x86) GetProcAddress (hModule, "GetDirVST2x86");
if (NULL != pGetDirVST2x86) {
LPWSTR lpszVST2x86;
pGetDirVST2x86(lpszVST2x86);
wprintf(lpszVST2x86);
}
FreeLibrary(hModule);
}
}
Here's the output:
C:\Program Files (x86)\Steinberg\VstPlugins
Here's the IDA screenshot of the function I want to use:
Pascal Script equivalent of the C declaration should be:
function GetDirVST2x86(lpString1: string): Integer;
external 'GetDirVST2x86#files:R2RINNO.DLL stdcall setuponly';
(i.e. no var, as it is an input character pointer argument).
Assuming the function contract is that you (as a caller) allocate a buffer and provide it to the function to be filled in, you should call the function like this:
var
Buf: string;
begin
{ Allocate buffer for the result large enough according to the API specification }
SetLength(Buf, 1000);
GetDirVST2x86(Buf);
SetLength(Result, Pos(#0, Result) - 1);
end;
See also How to return a string from a DLL to Inno Setup?
Hi everyone and thank you for your time. This was created in Visual Studio 2012,and I'm using the standard Windows Libraries.
I am attempting to call a DLL function explicitly and I believe the code I've written is correct; however, I am receiving an error. I'm not sure if it's an error in something that I've written in the small C console application or from the DLL which I do not have access to the internal workings of.
//global area
HINSTANCE _createInstance;
typedef UINT (CALLBACK* LPFNDLLFUNCLOOKUP)(AccuInput*, AccuOut*);
LPFNDLLFUNCLOOKUP lpfnDllFuncCASSLookup;
typedef UINT (CALLBACK* LPFNDLLFUNCINIT)(BSTR);
LPFNDLLFUNCINIT lpfnDllFuncInit;
typedef UINT (CALLBACK* LPFNDLLFUNCCLOSE)();
LPFNDLLFUNCCLOSE lpfnDllFuncClose;
HMODULE unmanagedLib;
Here is my main function:
int main() {
// Load Library
BSTR configFile;
unmanagedLib = LoadLibraryA((LPCSTR) "AccuAddressUnMgd.dll");
// Initialize AccuAddress COM dll
lpfnDllFuncInit = (LPFNDLLFUNCINIT)GetProcAddress(unmanagedLib, (LPCSTR)"Init");
// This function will lookup the address
lpfnDllFuncCASSLookup = (LPFNDLLFUNCLOOKUP)GetProcAddress(unmanagedLib, (LPCSTR)"AccuCassLookup");
// This function will call AccuAddress COM DLL Close function
lpfnDllFuncClose = (LPFNDLLFUNCCLOSE)GetProcAddress(unmanagedLib, (LPCSTR)"Close");
// Append “config.acu” file path.
configFile = SysAllocString(L"C:\PathTo\Config.acu");
printf("ConfigPath created");
lpfnDllFuncInit(configFile);
printf("ConfigFile consumed");
SysFreeString(configFile);
return 0;
}
This is the error that I receive:
Unhandled exception at at 0x75D4C54F in RDISample1.exe: Microsoft C++ exception: _com_error at memory location 0x001AFAC0.
The error occurs at:
lpfnDllFuncInit(configFile);
So, I guess my question is two parts. Based off the code can I say for a fact that the error is in the DLL function?
Second question, when calling GetProcAddress what would be the point (if any) for encapsulating the string in LPCSTR like a function versus typecasting?
ie
lpfnDllFuncClose = (LPFNDLLFUNCCLOSE)GetProcAddress(unmanagedLib, LPCSTR("Close"));
Thanks again for the help. I've been doing a fair amount of research yet DLLs still have been puzzled.
The initial error is caused by the library you're using failing to correctly handle a file that doesn't exist.
The path you gave contains single slashes \, which are treated as escape characters, not path separators. Path separators must be escaped, i.e. \\ to be treated correctly.
There is no point casting a string literal to LPCSTR.
As for the _com_error that is definitely coming from the DLL. I would suggest wrapping that in a:
try
{
...
} catch(_com_error const & e)
{
wprintf(L"Caught a com error: %s\r\n", e.ErrorMessage());
}
And then you might be able to figure out what is wrong.
I want to add a requireable module solely from the C API.
--lua.lua
local c_module = require("c_module")
c_module.doWork()
What API functions do I have to use to make this possible?
When loading a shared library with require, Lua looks for a a function named luaopen_<name> where <name> is the module name with the dots replaced with underscores (so require "foo.bar" will look for luaopen_foo_bar, but hyphens get special treatment; see the Lua manual).
This function should be a regular lua_CFunction; that is, it takes a lua_State* as an argument and returns an int. require calls this function with the package name as an argument, and the value you return from the function is what require stores and returns.
Here's an example for a module named foo:
static int bar(lua_State* L) {
// ...
}
int luaopen_foo(lua_State* L) {
lua_newtable(L); // Create package table
// Push and assign each function
lua_pushcfunction(L, &bar);
lua_setfield(L, -2, "bar");
// ...
// Return package table
return 1;
}
(This is for Lua 5.1, though the equivalent code for 5.2 should be very similar, if not the same. Also be sure that the luaopen_ function is exported from the shared library.)
The full behavior of the C loader can be found here: http://www.lua.org/manual/5.1/manual.html#pdf-package.loaders
I write my dll files in visual studio 2010.
The dll file (name fservice.dll), which has an external function, code write in c++ (VS2010, I have dll and lib files)
char * convert(char *)
Dll file witch has c-function, who exports and imports to postgresql:
typedef char* (__cdecl *MYPROC)(char * value);
PG_FUNCTION_INFO_V1(transform);
Datum
transform (PG_FUNCTION_ARGS)
{
HINSTANCE hinstLib= LoadLibrary("fservice.dll");
char * pointer;
text *t = PG_GETARG_TEXT_P(0);
if (hinstLib != NULL)
{
ProcAdd = (MYPROC) GetProcAddress(hinstLib, "convert");
pointer=ProcAdd("text");
FreeLibrary(hinstLib);
}
/*
* code
*/
PG_RETURN_TEXT_P(new_t);
}
I have a problem because, mod is doesn't exists. Path to dll file I check before write.
Compile this c-function, and when i debug i saw it HINSTANCE hinstLib it wasn't created. It wasn't NULL or any value, It wasn't exist. Finally my c-function doesn't use my function form external dll.
How load dll and use my external function ?
My external function form dll and LoadLibrary() is not called by dll program with called by Postgresql, Why?
this may be a simple answer, but what I don't see is a create function call. It would be something like:
CREATE OR REPLACE FUNCTION transform(text) RETURNS text LANGUAGE C AS
'/path/to/dll', 'transform';
Until you create the function, PostgreSQL doesn't know to dynamically load the dll....
I have a callback inside a C DLL (static void __stdcall) . I want another program to register it as such (by passing it the func ptr) and then call the calback inside the DLL. I have had no luck so far. However, the same callback works if its inside a regular C++ program. I am now wondering if having callbacks in a DLL is even possible. Any help will be appreciated!
Thanks.
Adding some code:
C# app:
[DllImport("DLLfilename.dll")]
public static extern void DLL_SetCallback(CallbackDelegate pfn);
public delegate void CallbackDelegate();
//setDelegate() is called in init() of the C# app
public void setDelegate()
{
CallbackDelegate CallbackDelegateInstance = new CallbackDelegate(callback);
DLL_SetCallback(CallbackDelegateInstance);
}
public void callback()
{
//This is the function which will be called by the DLL
MessageBox.Show("Called from the DLL..");
}
C DLL:
//is linked to externalLibrary.lib
#include "externalLibrary.h"
typedef void (__stdcall CallbackFunc)(void);
CallbackFunc* func; //global in DLL
//Exported
extern "C" __declspec(dllexport) void DLL_SetCallback(CallbackFunc* funcptr)
{
//setting the function pointer
func = funcptr;
return;
}
//Exported
extern "C" __declspec(dllexport) void RegisterEventHandler(Target, Stream,&ProcessEvent , NULL)
{
//ProcessEvent is func to be caled by 3rd party callback
//Call third-party function to register &ProcessEvent func-ptr (succeeds)
...
return;
}
//This is the function which never gets called from the 3rd party callback
//But gets called when all the code in the DLL is moved to a standard C program.
void __stdcall ProcessEvent (params..)
{
//Do some work..
func(); //Call the C# callback now
return;
}
Your question is a little confusing. Are you saying that you have a non-exported function within a DLL, which you wish to take the address of and pass to some external code, which will call it back? That's perfectly reasonable to do. If it's not working, here are the things to look at.
1) Make sure that the calling convention is correct on the definition of the function, the type of the function pointer within your DLL, and the type of the function pointer as declared in the external code.
2) Within your DLL, attempt to call the callback through the same function pointer that you're passing to the external code.
3) If (1) is correct, and (2) works, then fire up your debugger, put a breakpoint on the line where you're trying to call the callback from external code, and then drop into disassembly. Step through the call and see where it ends up.