C语言生成dll,返回字符串,调用问题

编译的时候没出问题,运行的时候,老是说test.exe执行过程中遇到问题,需要关闭。。。求救

cl /c hello.cpp
link /def:hello.def dll hello.obj
cl /c test.cpp
link test.obj hello.lib
最后生成test.exe

hello.cpp如下::

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

//extern "C" _declspec(dllexport) int __stdcall 没加上调用约定,会报错
//extern "C" _declspec(dllexport) char* __stdcall encPass(char* name)
char *say_hello(char* name)
{
static char encPass[50];
encPass[0]="a";
encPass[1]="b";
return encPass;
}

hello.def如下::
LIBRARY "hello"

EXPORTS

say_hello @1

test.cpp如下::
#include <stdio.h>

extern char *say_hello(char* name);

int main(int argc,char** argv)
{
say_hello("111"); //执行此处不报错
printf("%s",say_hello("111")); //执行此处报错:遇到问题需要关闭
return 0;
}

say_hello()中返回了局部变量,局部变量在函数运行结束之后就释放了,所以产生了非法引用.

在动态库中 要用GlobalAlloc来动态分配内存,在主程序中用GlobalFree来释放内存
温馨提示:答案为网友推荐,仅供参考
相似回答