0

I understand that the DLL typically has its own heap that it stores variables in. My DLL function takes a pointer to a wchar_t variable, and whenever I try to put a value in it, it simply exits the function, leaving the pointer pointing to a bad location which I'm assuming is because the heap gets destroyed.

If my DLL function comes up with some sort of data that needs to be passed back, could someone give me an example of how I could get that data in string format back to the original main function?

Using Visual Studio 2010.

Edit: I can provide some sample code, but I didn't see the point since I'm simply asking for an example/ explanation as to how memory is handled with regards to dll's and their functions. Ask me what information you need and I'll try to deliver.

Well, to give you guys an idea as to what the application does, it's a COM server DLL. The interface is IProperty, the object is called PropertyObject. The DLL was built separately, by me, with the PropertyObject methods. This method, Getproperty, is the one I'm working on.

STDMETHODIMP PropertyObject::GetProperty(int arg1, wchar_t* arg2)
{
    arg2 = L"Test";
    cout << *arg2 << endl;
    return S_OK;
}

int main()
{

CoInitialize(NULL);

IClassFactory * pClassFactory = NULL;
HRESULT hr;
hr  = CoGetClassObject(
CLSID_PropertyObject,
CLSCTX_SERVER,
NULL,
IID_IClassFactory,
(void **) &pClassFactory);

if (SUCCEEDED(hr))
{
    wchar_t x = NULL;
    IProperty *pProperty = NULL;

    hr = pClassFactory->CreateInstance(NULL, IID_IProperty, (void **) &pProperty);
    hr = pProperty->GetProperty(2, &x);
    cout << x << endl;
}
    return 0;
}
4

2 回答 2

0

如果您 100% 确定所有参与的程序都是使用相同版本的 Visual Studio 编译的(这意味着它们都使用 std::string 所属的相同版本的 STL),则可以使用 std: :字符串类。

如果它需要可互操作,最好的办法是传入一个 char* 和一个长度并写入提供的缓冲区。让调用者处理内存。这是相当 C 风格的,但也是您最安全的选择。

于 2013-03-12T16:53:01.153 回答
0

结果我还在考虑像普通字符数组一样的 wchar_t 指针。这是我修改后的代码:

STDMETHODIMP PropertyObject::GetProperty(int arg1, wchar_t* arg2)
{
    wcscpy(arg2, L"Test"); // This is the function that i needed to be using. 
    return S_OK;
}



int main()
{
    CoInitialize(NULL);

IClassFactory * pClassFactory = NULL;
HRESULT hr;
hr  = CoGetClassObject(
CLSID_PropertyObject,
CLSCTX_SERVER,
NULL,
IID_IClassFactory,
(void **) &pClassFactory);

if (SUCCEEDED(hr))
{
    wchar_t *x = new wchar_t; // Before, this was a normal variable. Changed it to a pointer. 
    IProperty *pProperty = NULL;

    hr = pClassFactory->CreateInstance(NULL, IID_IProperty, (void **) &pProperty);
    hr = pProperty->GetProperty(2, x); // Passed the pointer instead of an address to a normal variable. 
    wcout << x << endl; // wcout instead of cout. It worked. 
}
    return 0;
}
于 2013-03-12T18:27:15.887 回答