//请注意,在以上的“#include”语句中,我们没有加入DLL的头文件
//因为就是加了才无法通过编译,这里我们用一种处理无头案的方法来解决那些非我族类的DLL int status;
char message[80];
int main (int argc, char *argv[]) {
/*请注意以下几个声明,它们可是很重要的!!!*/ HMODULE hinstLib;
DLLCdeclFunction DLLFunction;
BOOL fFreeResult, fRunTimeLinkSuccess = FALSE;
/*-------------------------------------------------------------------------------------------------------*/
if (InitCVIRTE (0, argv, 0) == 0) /* Needed if linking in external compiler; harmless otherwise */
return -1; /* out of memory */
/*-------------------------------------------------------------------------------------------------------*/
// Get a handle to the DLL module. //装载动态链接库mydll.dll
hinstLib = LoadLibrary(\"mydll.dll\");
// If the handle is valid, try to get the function address. if (hinstLib != NULL)//成功装载动态链接库mydll.dll {
DLLFunction = (DLLCdeclFunction)GetProcAddress(hinstLib, (LPCSTR)\"MyDLLCdeclFunction\"); //取函数指针地址
// If the function address is valid, call the function.
if (fRunTimeLinkSuccess = (DLLFunction != NULL)) //dll中有函数MyDL
LCdeclFunction() {
Fmt(message, \"message via DLL function\\n\");
status = (long int)DLLFunction (message);//调用dll函数!!! }
// Free the DLL module
fFreeResult = FreeLibrary(hinstLib);//卸载动态链接库mydll.dll }
// If unable to call the DLL function, use an alternative if (! fRunTimeLinkSuccess) {
MessagePopup (\"Function Load Error\"); }
/*-------------------------------------------------------------------------------------------------------*/ return 0; }
通过以上的代码你应该明白它是如何工作的了吧! 这是MyDLLCdeclFunction的函数原形:
extern \"C\" long int DLLIMPORT MyDLLCdeclFunction(char * dummycharname);
DLLFunction 是指向函数的指针 message 是传给该函数的参数 status 是该函数的返回值 4、乘龙快婿
新出的CVI 8.5有了一个新特性:可以用在Visual.Studio.2005的VC中新建、添加CVI的工程
这样对于在CVI中使用DLL我们又有了一个新的思路,把作好的CVI用VC2005打开,然后在VC中加载DLL给CVI使用!但是实际作了以后,你会发现当你在VC2005中在CVI的头文件中“#include \"mydll.h\" ”后,编译器会给出与CVI下同样的错误提示! 解决的办法也有:我们可以在VC2005内先加载CVI工程,可以看到都是“*.h *.c”文件,用“Add new file to Item”在工程内新加一个“*.cpp”及“*.h”,现在在新加的文件里再调用之前的头文件及DLL看看结果如何?
5、移情别恋
JAVA中有一种JNI技术可以在JAVA中调用DLL,也同样可以把JAVA作成DLL。我们看一下在JAVA中调用DLL的方法: 我们要在JAVA中调用hello.dll JAVA代码: class HelloWorld {
public native void displayHelloWorld(); static {
System.loadLibrary(\"hello\");//此句重要 }
public static void main(String[] args) { new HelloWorld().displayHelloWorld(); } } 编译!
javac HelloWorld.java //得到HelloWorld.class javah HelloWorld // 得到 HelloWorld.h
这个h文件相当于我们在java里面的接口,这里声明了一个Java_HelloWorld_displayHelloWorld (JNIEnv *, jobject);方法,然后在我们的本地方法里面实现这个方法,也就是说我们在编写C/C++程序的时候所使用的方法名必须和这里的一致 VC代码:
#include 2 #include \"HelloWorld.h\" 3 #include 4 JNIEXPORT void JNICALL Java_HelloWorld_displayHelloWorld(JNIEnv *env, jobject obj) {
printf(\"Hello world!\\n\"); return; }
生成动态库!
运行程序
java HelloWorld 屏幕输出:Hello world!