如何在 C++/CLI 代码中初始化非托管静态指针?
我无法在托管类中初始化静态本机指针。
详细信息如下:我创建了一个 C++/CLI 控制台项目并在内部声明了一个静态非托管指针。但是,我无法用任何方法初始化静态指针(但是如果我将指针放入匿名命名空间中,就没有问题,在代码中进行了演示)。您是否遇到过类似的情况并有解决方案?
代码在这里:
class MyTask
{
public:
int m_index;
MyTask()
{
m_index = 0;
}
};
namespace
{
static MyTask* s_pTask;
}
public ref class MyApplication
{
public:
static MyTask* sm_pTask;
static void InitizlizeStaticMembers(MyTask* pTask)
{
sm_pTask = pTask;
}
void AddTask()
{
sm_pTask = new MyTask();
}
};
void main()
{
MyApplication^ app = gcnew MyApplication();
// 1st, doesn't work (sm_pTask is still null after the execution)
MyApplication::sm_pTask = new MyTask();
// 2nd, doesn't work (pTask can be initialized correctly, sm_pTask is still null after the execution)
MyTask* pTask = new MyTask();
MyApplication::InitizlizeStaticMembers(pTask);
// 3rd, doesn't work (sm_pTask is still null after the execution)
app->AddTask();
// 4th, work(s_pTask can be initialized correctly)
s_pTask = new MyTask();
}
I'm not able to initialize a static native pointer inside a managed class.
Here's the detail: I created a C++/CLI console project and declared a static unmanaged pointer inside. However I can't initialize the static pointer with any means (but if I put the pointer into an anonymous namespace, there's no problem, demoed in the code). Did u meet similar situations and got solutions for it?
Code here:
class MyTask
{
public:
int m_index;
MyTask()
{
m_index = 0;
}
};
namespace
{
static MyTask* s_pTask;
}
public ref class MyApplication
{
public:
static MyTask* sm_pTask;
static void InitizlizeStaticMembers(MyTask* pTask)
{
sm_pTask = pTask;
}
void AddTask()
{
sm_pTask = new MyTask();
}
};
void main()
{
MyApplication^ app = gcnew MyApplication();
// 1st, doesn't work (sm_pTask is still null after the execution)
MyApplication::sm_pTask = new MyTask();
// 2nd, doesn't work (pTask can be initialized correctly, sm_pTask is still null after the execution)
MyTask* pTask = new MyTask();
MyApplication::InitizlizeStaticMembers(pTask);
// 3rd, doesn't work (sm_pTask is still null after the execution)
app->AddTask();
// 4th, work(s_pTask can be initialized correctly)
s_pTask = new MyTask();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我发现(使用VS2005)调试器证实了你所说的——指针的值在更新时不会改变。但如果你让它输出一些东西,代码实际上是有效的。
我相信这是调试器中的一个错误。
I found that (with VS2005) the debugger confirms what you said - the value of the pointer doesn't change as it gets updated. But the code is actually working if you make it output something.
I believe this is a bug in the debugger.
我没有看到代码有任何问题,它对我来说工作得很好。不需要匿名名称空间。
I don't see any issue with the code and it works fine for me. The anonymous namespace is not needed.