LabVIEW

cancel
Showing results for 
Search instead for 
Did you mean: 

Dereference pointer returned from a dll

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"

 

 

 DllPointerSnippet.png

 

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

 

 

 

 

0 Kudos
Message 1 of 3
(3,162 Views)

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.

Rolf Kalbermatter
My Blog
0 Kudos
Message 2 of 3
(3,112 Views)

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

0 Kudos
Message 3 of 3
(3,008 Views)