Link to home
Start Free TrialLog in
Avatar of wjacky
wjacky

asked on

writing DLL library in VC++ problem

Hi, Expert,

I've done an external function as following,
char* abc()
{
    return "testing";
}

I generated the "test.dll" file for the above coding in VC++,
and I wanna get it connected with the VB by the following coding,

Declare Function abc lib "test.dll" () As String

When I call the function, it returns an error message of "memory cannot be
read"

but, when I declare the function as integer in both C++ and VB, it works.
So the point is, what data type should I declare in VB in order to get
connected with the C++ "char*" data type.

Thanks a lot!
Jacky



Avatar of PlanetCpp
PlanetCpp

the fact that your returning a constant string might be different to what im going to say but basically it's not good to return a char array and if you do that data has to be copied to a new variable or array. the fact that your going from char* to vb string is also different then what im saying but in c++ terms you cant return a char * and then try to use that pointer..it doesnt exist.
if in your function you create an array
char somearray[50] = {"whatever"};
then return somearray;
if you return that into a char pointer then you MIGHT get data that says "whatever" but that would only be by chance and only because the memory hasn't been overwritten yet.
once the function ends the memory space that was used for somearray is deallocated, not erased or zeroed out but just deallocated. so when the function returns and you try to use that pointer, your trying to access memory thats no longer allocated and youy'll get messed up results. bottom line, best thing for you to do is void the function and take it in vb as a sub or return int for some kind of fail/success indicator if needed, and try to make vb pass a string by referemce. I'm sure it'll work
so in your c++ function have it be
int abc(char *vbstring)
{
  strcpy(vbstring,"testing");
  return 1;
}
then to import into vb
declare function abc(byref vbstring as string) as integer
byref tells vb to pass as reference and im sure that'll work.
ASKER CERTIFIED SOLUTION
Avatar of BorlandMan
BorlandMan

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of wjacky

ASKER

Very clear explanation!
Thanks everyone!