简体   繁体   English

从DLL获取char *

[英]Get char * from DLL

I have a problem. 我有个问题。 I have a function in my dll which is defined as below: 我的dll中有一个函数,定义如下:

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: 我使用LoadLibrary在控制台应用程序中成功加载了我的dll,并使用函数指针调用我的函数:

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

then I pass my inVal to my function: 然后我将我的inVal传递给我的函数:

char * inVal = "input";

Now I want to get my outVal and retVal, I have got the retVal successfully but my outVal is NULL: 现在我想得到我的outVal和retVal,我已成功获得retVal,但我的outVal为NULL:

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

then I call my function: 然后我调用我的函数:

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

any clue?!! 任何线索?!!

EDIT 1: 编辑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 . 问题在于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; 你通过值传递outVal ,这意味着你在函数内部的指针是你传入的指针的副本。然后你用outVal = (char*)pemBuf.data;分配给那个指针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. pemBuf具有自动存储持续时间(因为它是function本地的),这意味着它将在返回时被销毁。 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 . 相反,你想要做的就是复制的内容pemBuf.data到在由指向数组元素outVal You can do this with std::copy or strcpy . 您可以使用std::copystrcpy执行此操作。 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). 但是,您还有另一个问题,即您没有传递缓冲区的大小(我不知道pemBuf.data数组的大小)。 Assuming you know how much to copy as N , however, you could do: 假设你知道要复制多少N ,你可以这样做:

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

However, your code is very C-like - using C-style strings, output parameters, and so on. 但是,您的代码非常类似C - 使用C风格的字符串,输出参数等。 I recommend that you start using std::string . 我建议你开始使用std::string

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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