ฉันได้เขียนไลบรารี C ++ พื้นฐานที่รับข้อมูลจากเซิร์ฟเวอร์ OPC UA และจัดรูปแบบเป็นอาร์เรย์ของสตริง (อักขระ **) ฉันยืนยันว่ามันทำงานแบบสแตนด์อโลน แต่ตอนนี้ฉันกำลังพยายามเรียกมันจากโปรแกรม C# ที่ใช้ DLLs/pInrigg และพบข้อผิดพลาดร้ายแรงของหน่วยความจำ
หลัก C # ของฉัน:
List<String> resultList = new List<string>();
IntPtr inArr = new IntPtr();
inArr = Marshal.AllocHGlobal(inArr);
resultList = Utilities.ReturnStringArray(/*data*/,inArr);
ฟังก์ชั่นตัวช่วย C #:
public class Utilities{
[DllImport(//DllArgs- confirmed to be correct)]
private static extern void getTopLevelNodes(/*data*/, IntPtr inArr);
public static List<String> ReturnStringArray(/*data*/,IntPtr inArr)
{
getTopLevelNodes(/*data*/,inArr); // <- this is where the AccessViolationException is thrown
//functions that convert char ** to List<String>
//return list
}
และสุดท้าย การใช้งาน C++ DLL ของฉัน:
extern "C" EXPORT void getTopLevelNodes(*/data*/,char **ret){
std::vector<std::string> results = std::vector<std::string>();
//code that fills vector with strings from server
ret = (char **)realloc(ret, sizeof(char *));
ret[0] = (char *)malloc(sizeof(char));
strcpy(ret[0], "");
int count = 0;
int capacity = 1;
for (auto string : results){
ret[count] = (char*)malloc(sizeof(char) * 2048);
strcpy(ret[count++], string.c_str());
if (count == capacity){
capacity *= 2;
ret = (char **)realloc(ret, sizeof(char *)*capacity + 1);
}
}
สิ่งที่ควรทำคือ เริ่มต้นรายการเพื่อเก็บผลลัพธ์สุดท้ายและ IntPtr ที่จะเติมเป็นอักขระ ** โดย C++ DLL ซึ่งจะถูกประมวลผลกลับใน C# และจัดรูปแบบเป็นรายการ อย่างไรก็ตาม AccessViolationException จะถูกส่งทุกครั้งที่ฉันเรียก getTopLevelNodes จาก C# ฉันจะทำอย่างไรเพื่อแก้ไขปัญหาหน่วยความจำนี้ นี่เป็นวิธีที่ดีที่สุดในการส่งอาร์เรย์ของสตริงผ่านการทำงานร่วมกันหรือไม่
ขอบคุณล่วงหน้า
แก้ไข: ฉันยังคงมองหาคำตอบเพิ่มเติม หากมีวิธีที่ง่ายกว่าในการใช้การทำงานร่วมกันของอาร์เรย์สตริงระหว่าง C# และ DLL โปรดแจ้งให้เราทราบ!
IntPtr[]
แทนIntPtr
แล้วในแง่หนึ่งคุณส่งผ่านอาร์เรย์ของพอยน์เตอร์ ไม่ใช่เพียงแค่พอยน์เตอร์ตัวเดียว นอกจากนี้ เช่นเดียวกับหมายเหตุด้านข้าง ฉันเชื่อว่าคุณมีหน่วยความจำรั่ว 1 อักขระสำหรับองค์ประกอบอาเรย์แรกของคุณ เนื่องจากคุณ malloc จุดสำหรับมัน จากนั้นเรียก malloc อีกครั้งในการวนซ้ำครั้งแรกของคุณ - person pstrjds   schedule 20.12.2016