2015-08-31 83 views
-5

我是C初學者。我在C中實現了一些代碼,它將調用一個接口函數,參數爲uint8_t *valuepass作爲緩衝區int32_t *length作爲緩衝區的長度傳遞如何將uint8_t *作爲緩衝區傳遞給函數

/*interface function declaration in header file 
* this interface implementation is not under my 
* control. I just call the following function. 
* The return value is 0(successful) or 1(fail) 
*/ 
int get_parameter(uint8_t *value, uint32_t *length); 

/*My .c File */ 
/*can it be passed as buffer? because the function will 
*assign some memory located value to this parameter. 
*uint8_t cant have value greater than 255 but in my 
*case the memory located value can be larger than 255 
*/ 
uint8_t value; 

/*Is it correct ? 
*This should be the length of the buffer declared above*/ 
uint32_t length = sizeof(value); 

/* interface function call in my code */ 
int result = get_parameter(&value, &length); 

if(result == 0) 
{ 
    char *data; 
    int32_t *myValue; /*want to assign what value parameter pointing to*/ 
    memcpy(data + sizeof(int32_t), &value, length); /*perhaps something like this ?*/ 

} 

值和長度/輸出參數。該接口函數將分配值,可以是<> 255,以賦值參數並將該值的長度以字節分配給長度參數。

我的問題是,如何調用接口函數int get_parameter(uint8_t *value, uint32_t *length),以便它可以爲值參數分配一些值,而與大小無關。我有點困惑值的參數,因爲uint8_t只能有最大值255,但在我的情況下,它可以大於255.我期待解決方案是這樣的。

char *value; 
uint32_t length = sizeof(value); 

/* interface function call in my code */ 
int result = get_parameter(value, &length); 

if(result == 0) 
{ 
    uint32_t *myValue; 
    *myValue = atoi(value); 
    printf("%d", *myValue); /*it should print whatever the value assigned by the get_parameter function*/ 
} 
+0

@SouravGhosh對不起,我沒有任何例子。我必須執行它。如果我有一個例子,我不需要問這個問題。我可以簡單地遵循示例代碼。 – Shawn

+0

「那個價值」是指什麼? – kaylum

+0

@shan我沒有要求例子的代碼,功能的例子輸入/輸出是我所要求的。請參閱[遊覽](http://stackoverflow.com/tour)並閱讀[如何提問](http://stackoverflow.com/help/how-to-ask),以便了解我們對問題的期望。 :) –

回答

1

假設get_parameter返回內存的int32_t通過value指出,這裏的去做一個辦法:

int32_t value; 
uint32_t length = sizeof(value); 

if(get_parameter((uint8_t *)&value, &length) == 0) 
{ 
    // value is an int32_t containing data set by get_parameter() 
} 

三種意見:

  1. 前面加上參數&(&符號)字符意味着取參數的地址,這只是sayi的另一種方式ng「指向」參數。

  2. (uint8_t *)投下的&value類型uint8_t *,所要求的get_parameter。類型轉換有時會皺眉,但難以避免;一種替代解決方案可以基於將uint8_t數組傳遞給get_parameter,然後使用memcpy將值複製回int32_t,但即使如此,在memcpy調用中也需要幾個(隱式)強制轉換。另外請注意,在投射從int32_t *uint_8 *通常工作時,從uint8_t *投射到int32_t *(或從任何較小到較大類型)可能會導致某些體系結構上的對齊問題。

  3. 最後,length是一個指針,這意味着get_parameter可能會返回實際寫入*value的字節數。如果是這種情況,那麼爲了保證正確性,您應該檢查length在致電get_parameter之後是否有預期的內容,即檢查length == sizeof(value)

+1

這沒有任何意義。您將一個長度爲1的緩衝區傳遞給一個函數,並期望它返回一定的長度。什麼樣的長度?如果這是結果的長度,結果應該適合什麼? –

+0

基於這個問題(已經編輯了很多次),我很難找出更好的答案。我最初認爲這是一個語法問題,即如何將指針傳遞給'value'和'length'。在不瞭解get_parameter的語義的情況下,我們所能做的只是猜測和/或要求更多信息。 –

+0

代碼無法自行理解,無論目前的措辭不佳。 –

相關問題