12-21-2015 09:26 AM
Hi,
I am trying to understand how to dereference pointers I receive from DLLs.
To test that I wrote a dummy DLL and I cannot even get that to work.
What am I doing wrong?
The DLL-Code is this (C++):
extern "C"
{
__declspec(dllexport) int* int_pointer(int)
{
int a = 55;
int* pointer_a = &a;
return pointer_a;
}
}
I am trying to dereference the pointer using "moveBlock"
But I do not get the right value (55) back. I either get something that looks like an memory address or I get the value of "Size of Int".
I have been checking all the tutorial I found on this, but I still could not figure out my mistake.
Do I have to allocate memory before using "malloc" in the DLL?
Thanks a lot for the help,
Andy
12-22-2015 05:24 AM
Your int a value is a stack variable. As such it is only valid for as long as the function executes and is then cleaned up before returning to the caller. At the time LabVIEW gets to execute the MoveBlock function this stack space has probably be reused umtien times already for other code execution. So you are not reading anymore what you wrote into that stack address but something else from code execution elsewhere.
If you want to fix this in a trivial way you need to make the variable a static.
static int a = 55;
But, static variables are globals and make all your DLL functions accessing that variable generally non-reentrant, so you will have to configure them to run in the UI thread when calling them from LabVIEW.
01-04-2016 02:54 AM
Thanks a lot for the response.
I also found another solution:
Allocate the memory with the new() (C++) or the malloc() (C) command.
Then the memory stays allocated until you deallocate it using delete() (after new() ) or free ( after malloc() ).
#include <iostream>
extern "C"
{
__declspec(dllexport) int* int_pointer(int)
{
int* ptrINT = NULL;
ptrINT=new int;
int a = 99;
*ptrINT = a; //
return ptrINT;
}
}