Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Pointer Returned from C Library in C++

Tags:

c++

I am using a library developed in C (particularly: HTK). I've made a bit modifications to source and trying to get a pointer (to beginning of a linked list) from a function. Not to go into too much detail; say I have a struct named OutType. In my C++ code I declare: OutType* Out; and pass it to some function LName(....., OutType* Out) Now, in the C library, LName takes parameter Out, and calles a function named SaveH where Out is the return value (Out=SaveH(...)) and in SaveH, Out is malloc'ed as OutType returnOut=(OutType*)malloc(1,sizeof(OutType)); As far as I see, Out is perfectly malloc'ed, and in LName function I can get the address of the memory area that was allocated. But when I return to my C++ code, where I call LName and pass Out as a parameter, that parameter always has 0 as the address. If I leave everything same, but just change SaveH so that Out is not a return value, but a parameter as SaveH(....,OutType* Out) and alloc that value in C++ code before passing everything is fine. Is it normal? Is there some problem with pointer allocated in C library, using in C++ code? Thanks

like image 378
paul simmons Avatar asked Aug 28 '26 08:08

paul simmons


1 Answers

You are passing a copy of the pointer, which is why the change in the C library isn't seen in your C++ code.

Since you're already modifying the library, you should have that C function take a pointer to a pointer.

LName(....., OutType** Out)

*Out=SaveH(...);

Now you'll be passing the address of the C++ pointer, so your C code will be modifying the same original pointer.

like image 200
Drew Dormann Avatar answered Aug 29 '26 21:08

Drew Dormann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!