There is such a simple function as follows, in Windows system compiled into a DLL file, using Powerbuild call, always can not get the correct results, the return is all messy code, if using C call this DLL, it can be successful. It should be noted that this DLL is compiled with Nim 1.4 x86 version, Pb does not support 64 bit. I want to understand, how to write DLL, can let Pb normal call.
proc test(output: var cstring) {.dynlib, stdcall, exportc.} =
output = "test".cstring
This is a C program call, run results show 'test' string, run without error.
#include
#include
int main()
{
typedef bool (*TEST)(char**); // Function pointer type
HINSTANCE Hint = LoadLibrary("test.dll"); // Load the generated DLL
TEST test = (TEST)GetProcAddress(Hint,"test@4"); // Get the method of DLL export
char *out;
test(&out);
printf("%s\n", out);
return 0;
}
This is the Powerbuild code, the external function declaration.
subroutine test(ref string out) library "test.dll" alias for "test@4;Ansi"
Call code:
string ls_out
ls_out = space(100)
test(ls_out)
messagebox('t',ls_out)
In your nim code, test() only return the pointer of string. This is danger behavior because the caller don't know when the string will be destroyed. The code works becasue "test" is static string and it won't be destroyed.
I have never used Powerbuild before, but in your code, it seems to create some buffer and then pass it to the test0 function. I think what you should do is to copy the string, not just to return the pointer of the string.
If I change the argument 'var cstring' to 'var char' to pass a character, PowerBuild it works fine, but I want to pass a string instead of a single character.
proc test(output: var char) {.dynlib, stdcall, exportc.} =
var tmp = '8'
output = tmp