简体   繁体   中英

Get char * from DLL

I have a problem. I have a function in my dll which is defined as below:

int function(char *inVal, char *outVal, int *retVal)

I successfully load my dll in a console application using LoadLibrary, and I call my function with function pointer:

typedef int (__cdecl *functionPtr)(char *, char *,int *);

then I pass my inVal to my function:

char * inVal = "input";

Now I want to get my outVal and retVal, I have got the retVal successfully but my outVal is NULL:

int retVal = 0;
char outVal[200] = {0};

then I call my function:

int return = functionLNK(inVal , outVal, &retVal)

any clue?!!

EDIT 1:

The code is as below:

int function(char *inVal, char *outVal, int *retVal) 

{

PKI_Buf inBuf, signBuf, pemBuf;

......


outVal = (char*)pemBuf.data;

//I check outVal in this point and it is not NULL

}

The problem is with function . You pass outVal by value which means that the pointer you have inside the function is a copy of the one you passed in. Then you assign to that pointer with outVal = (char*)pemBuf.data; . All you've done is modified the copy. No change occurs on the outside.

This isn't the only problem with your approach though. You're also trying to pass a pointer to a member of an object that is about to go out of scope. pemBuf has automatic storage duration (because it is local to function ) which means it will be destroyed when it returns. Then your pointer will be pointing at an invalid object.

Instead, what you want to do is copy the contents of pemBuf.data over to the array elements pointed at by outVal . You can do this with std::copy or strcpy . However, you have another issue which is you don't pass in the size of your buffer (and I don't know the size of the pemBuf.data array). Assuming you know how much to copy as N , however, you could do:

std::copy(pemBuf.data, pemBuf.data + N, outVal);

However, your code is very C-like - using C-style strings, output parameters, and so on. I recommend that you start using std::string .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM