2014-07-10 93 views
-1

我有一個C靜態庫,並在其中我有一個名爲returnBytes一個()的函數,這個函數的定義是這樣的:從靜態庫返回從AC函數的字符串(字符*)(.LIB)

extern "C" unsigned char * returnBytes(void) 
{ 
     static unsigned char result[50] = { 0xF0, 0xF0, 0xF0 }; 
     return result; 
} 
我的其他項目

其使用上述靜態庫(.LIB)我調用該函數是這樣的:

unsigned char *output = returnBytes(); 

,但是當我打印輸出,其不正確的內容。這意味着調用像這樣的自定義打印功能不返回正確的值:從庫中()

print_bytes(output, 50); 

在另一方面呼籲returnBytes工作正常。意思是打印值0xF0,0xF0,0xF0。

是否靜態關鍵字只有保持相同項目中的變量值?如果在從一個項目中調用的靜態庫函數中使用靜態關鍵字,那麼它是否會起作用?

我應該使用malloc來代替並將指針傳遞給returnBytes()?這是唯一的方法嗎?

我正在運行Windows 7,並使用VC12編譯庫和庫的客戶端。

+2

@AustinBrunkhorst,這是不正確的。他有一個'static'變量。 –

+0

哎呀,我忽略了這一點。 –

+2

*「不起作用」*非常模糊。你想告訴我們* actual *結果是什麼,它和* expected *結果有什麼不同?以及你如何證明這一點? (你使用'printf'?或更復雜的東西?) – abelenky

回答

1

編輯:對不起沒有注意到靜態。隨着靜態它的作品。 我剛剛在osx上測試了你的代碼,它的工作原理如下。

test.h:

#ifndef TEST_H 
#define TEST_H 
#ifdef __cplusplus 
extern "C" { 
#endif 
    unsigned char * returnBytes(void); 
#ifdef __cplusplus 
} 
#endif 
#endif /* TEST_H */ 

test.c的:

unsigned char * returnBytes(void) 
{ 
     static unsigned char result[50] = { 0xF0, 0xF0, 0xF0 }; 
     return result; 
} 

在其他項目建成一個圖書館libtest.a,並呼籲通過的main.c

#include <cstdlib> 
#include <cstdio> 
using namespace std; 

#include "./test.h" 

int main(int argc, char** argv) { 

    unsigned char *c = returnBytes(); 
    printf("%x %x %x\n", c[0], c[1], c[2]); 

    c[1]= 0xd0; 

    c = returnBytes(); 
    printf("%x %x %x\n", c[0], c[1], c[2]); 

    return 0; 
} 

的輸出爲

f0 f0 f0 
f0 d0 f0 

這意味着您可以讀取和寫入。

0

static只適用於你的功能。此外,任何常用變量(位於堆棧中)總是會在函數結束時死亡,因此是錯誤的結果。

要解決此問題,使用動態分配你的函數內:

unsigned char *result = calloc(50, 1); 
    result[0] = 0x50; 
    result[1] = 0x50; 
    result[2] = 0x50; 
    return result; 
+0

該變量被聲明爲「靜態」。函數返回時它不會死。 –

+0

我從來沒有這麼說過。這是爲其他人。對於靜態我說它只能在你的函數中工作(保持活着)。但也許我錯誤地提出了這個問題。 –

+1

函數可以返回一個'static'變量的地址。該地址在調用函數中有效。 '你在'功能內部活着'是什麼意思? –