尝试以相反的顺序使用 extern
当我们有一个exe
或dll
以及附加的静态库
时,我们可以使用extern
关键字从 exe
或 dll
访问静态库的变量
和/或函数
。为了让事情变得更简单,我们假设已经附加了一个 exe
和一个 lib
。
我想做的是从lib
调用exe
的函数。
可执行代码
void doSomething() {
// do something here
}
静态链接库代码
void onSomeEvent() {
doSomething(); // call doSomething() here
}
反之亦然很容易,但我想知道是否可以通过像 extern
关键字这样的方式来完成。或者什么是最好的方法?
我想到的是将函数指针
(如void*
)传递给函数
/方法 在
lib
中(可能是类构造函数)。我认为这应该可行,但我不想太多地接触库的代码,因为库不是我的,可以用更新的版本替换。我可以向其中添加/删除几行代码,但我想防止更改函数接口。
什么是更好的方法?
When we have an exe
or dll
and a static library
attached to it, we are able to use extern
keyword to access static library's variables
and/or functions
from the exe
or dll
. To make things simpler, let's assume ve have an exe
and a lib
attached to it.
What I am trying to do is to call a function of exe
from lib
.
Executable Code
void doSomething() {
// do something here
}
Static Linked Library Code
void onSomeEvent() {
doSomething(); // call doSomething() here
}
Vice versa is easy but I wonder if this can be done in a way like extern
keyword. Or what is the best method?
What comes to my mind is to pass a function pointer
(like void*
) to one of the functions
/ methods
in the lib
(probably to a class constructor). I think this should work but I don't want to touch library's code too much since library is not mine and can be replaced with newer versions. I can add/remove a few lines of code to it but I want to prevent from changing function interfaces.
What is the better way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您也可以在函数之外声明它,您可能有其他函数需要它。
You may also declare it outside your function, you may have other functions need it.
当然,您只需在库中声明该函数即可。
Of course, you merely have to declare the function in the library.
鉴于静态库(可能)要在许多不同的程序中使用,因此使用回调方法并不少见,其中 exe 初始化库并向其传递一个或多个函数指针以用于执行操作(例如记录消息,或任何)。如果 exe 不传入函数指针(或将它们作为
NULL
传递),那么库就不能调用这些函数,并且库将在两种环境中正常工作。这比假设函数始终在 exe 中定义要好得多。
Given the static library is (probably) meant to be used in many different programs, it's not uncommon to use the callback approach where the exe initialises the library and passes it one or more function pointers to use to do things (like logging messages, or whatever). If the exe doesn't pass in the function pointers (or passes them as
NULL
) then the library can simply not call those functions and the library will work well in both environments.This is much better than assuming the functions are always defined in the exe.