将模板指针转换为字符指针时 C++ 不执行代码

问题描述

Cygwin 3.2.0
cmake 3.

你好,我是 C++ 新手(昨天刚开始),所以我对指针并不完全熟悉。据我了解,指针只是某事物的第一个索引的内存中的一个位置,编译器会在增量时自动将指针地址缩放为指向的任何内容。从下面的代码输出来看,这是 Cywgin 编译器中的错误还是我使用的指针错误? (除了下面显示的用于捕获异常的 try/catch 语句之外,没有其他 try/catch 语句)。

方法 _put 是从方法 write 调用的,类 V 与写泛型相同。在下面的代码中,我试图执行 _put<short>(2)。我希望程序抛出异常或打印 "From DLL\nWorking from DLL" 并返回 1在这种情况下,这两种情况都没有发生,这让我感到困惑,为什么没有正确执行 put 方法代码的第二部分,以弄清楚发生了什么。

//Code buried in a shared library (.dll)
//Trial 1 Code
template<class V>
void _put(long long index,V v){
    std::cout << std::endl << "From DLL";
    //void* t = (void*) v; //Works
    char* t = (char*) v; //Fails
    std::cout << std::endl << "Working from DLL?" << t;
}

//Code buried in a shared library (.dll)
//Trial 2 Code
template<class V>
void _put(long long index,V v){
    std::cout << std::endl << "From DLL";
    void* t = (void*) v; //Works
    //char* t = (char*) v; //Fails
    std::cout << std::endl << "Working from DLL?" << t;
}
//Exe code using the shared library
int main() {
    std::cout << "From Exe";
    try {
        Memory m(2000);
        m.write<short>(2);
        std::cout << m.get<char>() << "Test";
        return 1;
    }catch(const std::exception& ex){
        std::cerr << "Error : " << ex.what() << std::endl;
        throw;
    }
}

试验 1 代码输出

From Exe 
From DLL
Process finished with exit code 0

试验 2 代码输出

From Exe
From DLL
Working from DLL?0x2 Test
Process finished with exit code 1

解决方法

如果您打算这样做:

char* t = (char*) v;
std::cout << std::endl << "Working from DLL?" << t;

那么 v 需要指向一个有效的(C 风格)字符串,而且很可能不是。

如果您打算将 t 作为原始地址打印出来,那么您可以这样做:

std::cout << std::endl << "Working from DLL?" << (void *) t;