2013-04-26 86 views
0

將C代碼中的鏈表傳遞給C++有哪些已知問題? 我有一個Qt對話框,我將其添加到傳統C代碼中。 Qt類(在C++庫中)調用C庫函數,該函數返回指向鏈接列表的靜態指針。該列表在C庫中創建。例如:將鏈表從C傳遞到C++

的C代碼:

typedef my_struct_s my_struct_t, *my_struct_p; 
struct { 
    int some_data; 
    double some_more_data; 
    my_struct_p next; 
} my_struct_s; 
void create_list() 
{ 
    my_struct_p next; 
    SP_head = (my_struct_p) calloc(1, sizeof(my_struct_t)); 
    next = (my_struct_p) calloc(1, sizeof(my_struct_t)); 
    SP_head->some_data = 1; 
    next->some_data = 2; 
    SP_head->next = next; 
} 
static my_struct_p SP_head=(my_struct_p)0; 

extern my_struct_p get_list() { 
    if(!SP_head) 
    create_list(); 
    return SP_head; 
} 

C++代碼:

myclass::do_something() 
{ 
    my_struct_p list = get_list(); 
    for(my_struct_p ptr = list; ptr; ptr = ptr->next) 
    { 
     std::cout << ptr->value; 
    } 
} 

SP_head有效且包含一串條目的時候我獲得它。在我的調試器中,我可以看到下一個條目已填充,並且從函數get_list()返回時有效。

當我嘗試分配ptr=ptr->next時,無論是在for循環中,還是在while循環結束時或通過臨時指針,值都是null。即

temp_ptr = ptr->next; 
// temp_ptr is null 
// but I can see ptr->next looks ok in a debugger 

我已經更改了代碼,將列表中的每個元素複製到一個數組中,並返回該數組,並且它工作正常。這是否與堆棧有關,與C和C++不兼容,還是隻是表明我在其他地方有內存問題?

+5

看到'my_struct'可能會有幫助,沿着其他typedefs。此外,你的代碼看起來不正確('get_head()'應該返回'my_struct_p',而不是'my_struct'),這表明這可能不是真實代碼,因此進一步使得準確的答案更加困難。一個[SSCCE](http://www.sscce.org)會非常有幫助,並且在寫它時你可能會在沒有任何幫助的情況下發現你的問題。最後,你在編譯debug-no-optimizations嗎?除非您準備好進入asm,否則不要信任發佈代碼上的調試器。 – WhozCraig 2013-04-26 17:08:17

+0

我看不到如何看my_struct會有所幫助。它只是一個帶有下一個指針的普通舊結構。以上只是僞代碼,是的,函數應該返回一個my_struct_p。當然,我正在編譯我的調試模式,沒有優化。問題在於是否存在與上述概念有關的已知問題。如果沒有,那麼我知道我需要在早期尋找一個bug。 – mike 2013-04-29 09:55:13

+0

編輯顯示示例結構和用法 – mike 2013-04-29 10:04:06

回答

0

當然,C++是準備處理C,那麼你應該假設有沒有不兼容使用適當接口時。

畢竟,在C中實現了許多SW並且從C++接口。我正在使用,例如,SWI-Prolog - 以C語言實現 - 來自Qt。

但是編譯代碼,我不得不做一些變化:這裏的底線

文件my_list.h

#ifdef __cplusplus 
extern "C" { 
#endif 

struct my_struct_s { 
    int some_data; 
    double some_more_data; 
    struct my_struct_s *next; 
}; 
typedef struct my_struct_s my_struct_t, *my_struct_p; 

void create_list(); 
extern my_struct_p get_list(); 

#ifdef __cplusplus 
} 
#endif 

文件my_list.c

#include "my_list.h" 
#include <stdio.h> 
#include <stdlib.h> 

static my_struct_p SP_head=(my_struct_p)0; 

void create_list() 
{ 
    my_struct_p next; 
    SP_head = (my_struct_p) calloc(1, sizeof(my_struct_t)); 
    next = (my_struct_p) calloc(1, sizeof(my_struct_t)); 
    SP_head->some_data = 1; 
    next->some_data = 2; 
    SP_head->next = next; 
} 

my_struct_p get_list() { return SP_head; } 

文件爲主。 cpp

#include "my_list.h" 
#include <iostream> 

class myclass { 
public: 
    void do_something() 
    { 
     my_struct_p list = get_list(); 
     for(my_struct_p ptr = list; ptr; ptr = ptr->next) 
     std::cout << ptr->some_data << std::endl; 
    } 
}; 

int main() { 
    create_list(); 
    myclass c; 
    c.do_something(); 
} 

現在編譯並運行:

g++ my_list.c main.cpp 
./a.out 
1 
2