ฉันกำลังพยายามเขียน wrapper C++/CLI โดยใช้ VS2010 กับ C++ API ซึ่งฉันมีสิทธิ์เข้าถึงเฉพาะไฟล์ส่วนหัวและไฟล์ dll/lib เท่านั้น
ฉันประสบปัญหากับการสำรองข้อมูลการอ้างอิงเนทิฟจากโค้ดเนทีฟไปยังการอ้างอิงการติดตามในโค้ด C# ฉันได้รับ SystemAccessViolation รหัสมีดังนี้:
ส่วนหัว C++ ดั้งเดิมที่ไม่ได้รับการจัดการสำหรับฟังก์ชันดั้งเดิมที่ส่งคืนการอ้างอิงเพื่อสร้างและแก้ไข CustomObject:
class ManageCustomObject;
_declspec(dllimport) errorCode CreateCustomObject(CustomObject& customObject);
_declspec(dllimport) errorCode ModifyCustomObject(CustomObject& customObject);
สิ่งสำคัญที่ควรทราบเกี่ยวกับ CustomObject คือมีตัวสร้างส่วนตัวเท่านั้น:
CustomObject(const CustomObject&) { }
CustomObject& operator=(const CustomObject&) { return *this; }
ตอนนี้วิธีเลเยอร์ C++/CLI ของฉันมีลักษณะดังนี้:
public ref class WrapperManageCustomObject {
public:
errorCode WrapperCreateCustomObject(CustomObject% customObject)
{
return CreateCustomObject(customObject);
}
errorCode WrapperModifyCustomObject(CustomObject% customObject)
{
return ModifyCustomObject(customObject);
}
};
และ wrapper สำหรับ CustomObject มีลักษณะดังนี้:
public class WrapperCustomObject : public CustomObject {
public:
WrapperCustomObject(const CustomObject&) {};
};
ใน C# รหัสจะเป็นดังนี้:
WrapperCustomObject wrapperCustomObject;
WrapperManageCustomObject wrapperManageCustomObject = new WrapperManageCustomObject();
long result;
// this works great
result = wrapperManageCustomObject.CreateCustomObject(ref wrapperCustomObject);
// can utilize wrapperCustomObject here with other native functions no problem, so long as I don't try to modify it...
...
// this throws an AccessViolationException was unhandled message
// essentially I am modifying / returning a different native customObject (though I'm not 100% sure what it does as I do not have access to the code)
result = wrapperManageCustomObject.ModifyCustomObject(ref wrapperCustomObject);
ดังที่คุณเห็นในความคิดเห็นของฉัน ความพยายามที่จะแก้ไขวัตถุนั้นผ่านการอ้างอิงทำให้เกิดข้อผิดพลาด "AccessViolationException was unhandled : พยายามอ่านหรือเขียนหน่วยความจำที่ได้รับการป้องกัน นี่มักจะบ่งชี้ว่าหน่วยความจำอื่นเสียหาย"
ตอนนี้ ถ้าฉันลบ C# และการอ้างอิงการติดตามออกจากสมการนี้ และทำทั้งหมดนี้ภายใน C++ หรือ C++/CLI (ตราบใดที่ไม่มีการอ้างอิงการติดตาม) ก็ใช้งานได้ดี ฉันคิดว่านี่เกี่ยวข้องกับโค้ดเนทีฟที่พยายามเข้าถึงการอัปเดตข้อมูลอ้างอิงที่ขณะนี้อยู่ในพื้นที่ที่ได้รับการจัดการ
มีวิธีใดในการทำให้โค้ดนี้ "ใช้งานได้" จากภายใน C # หรือไม่ ไม่มีวิธีใดที่จะส่งผ่านการอ้างอิงดั้งเดิมไปยัง C# ที่ฉันทราบได้
CustomObject
ในที่ดิน C ++ อย่างไรหากมีตัวสร้างส่วนตัวและไม่มีฟังก์ชันจากโรงงาน คุณต้องมีอินสแตนซ์CustomObject
อยู่แล้วจึงจะสามารถเรียกใช้ฟังก์ชันตัวช่วยCreateCustomObject
ได้ - person Adam Rosenfield   schedule 06.08.2011@
เพื่อให้พวกเขาได้รับการแจ้งเตือนในกล่องจดหมาย SO ของพวกเขา - person ildjarn   schedule 06.08.2011private: CustomObject* _customObject;
และใช้การดำเนินการกำจัดและตัวสรุปเพื่อให้แน่ใจว่าได้รับการทำความสะอาด - person ildjarn   schedule 06.08.2011