简体   繁体   English

如何在 C 中的项目之间共享函数符号和地址?

[英]How to share functions symbols and addresses between projects in C?

I have two distinct projects which are running on the same target.我有两个不同的项目在同一个目标上运行。 I want my second project to use few functions written in the first project at specific addresses.我希望我的第二个项目在特定地址使用第一个项目中编写的几个函数。

To do that I thought I could use the symbol table from the first project in the second but it doesn't work.为此,我认为我可以在第二个项目中使用第一个项目中的符号表,但它不起作用。 (I use arm-none-eabi toolchain and -nm on .elf file to generate symbols table). (我在 .elf 文件上使用 arm-none-eabi 工具链和 -nm 来生成符号表)。

I know that is possible but how can I do that ?我知道这是可能的,但我该怎么做?

Well, the brute-force approach will very likely work:好吧,蛮力方法很可能会奏效:

int (*far_function)(int a, int b, int c) = (int(*)(int, int, int)) 0xfeedf00d;

far_function(1, 2, 3);

In other words, just make a function pointer and initialize it using the known address.换句话说,只需创建一个函数指针并使用已知地址对其进行初始化。

If the address isn't well-known (which it won't be if the other application is re-built and you haven't taken steps to "lock" the target function to a particular address), I would instead add meta-data at some fixed address, that contains the pointer.如果地址不是众所周知的(如果其他应用程序被重新构建并且您没有采取措施将目标函数“锁定”到特定地址,则不会这样),我会改为添加元-某个固定地址的数据,其中包含指针。 The other application would embed this data, thereby "exporting" the location of the interesting function.另一个应用程序将嵌入此数据,从而“导出”感兴趣函数的位置。

The addresses yielded by nm are the location of the symbols, but on Cortex-M which used the Thumb2 instruction set, those addresses cannot be used directly for jump/call/branch execution - it is necessary to set the LSB of the address to 1 to indicate Thumb mode. nm 产生的地址是符号的位置,但在使用 Thumb2 指令集的 Cortex-M 上,这些地址不能直接用于跳转/调用/分支执行 - 必须将地址的 LSB 设置为 1以指示拇指模式。

For example:例如:

typedef void (*voidFn_void_t)(void) ;

uint32_t symbol_address = symbolLookup( "myfunction" ) ;

symbol_address |= 1 ;                // Make Thumb mode address
((voidFn_void_t)symbol_address)() ;  // Make call

The called function must even then have no dependencies on the execution environment since it is executing in the environment of the caller, not that of the project it was built in. You may get away with it if the execution environment is be identical but maintaining that may be a problem.被调用的函数甚至必须不依赖于执行环境,因为它是在调用者的环境中执行的,而不是它内置的项目。可能是个问题。

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

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