return custom struct as python object(which aslo could be none) #3591
              
                
                  
                  
                    Answered
                  
                  by
                    linrongbin16
                  
              
          
                  
                    
                      linrongbin16
                    
                  
                
                  asked this question in
                Q&A
              
            -
| I want to return a custom struct as a python object, which also could be none. I have tried two API: struct Database {
  UserModel *get_user1(const std::string &user_name) const;
  std::optional<UserModel> get_user2(const std::string &user_name) const;
};But it seems none of these two API works. | 
Beta Was this translation helpful? Give feedback.
      
      
          Answered by
          
            linrongbin16
          
      
      
        Jan 5, 2022 
      
    
    Replies: 1 comment
-
| Turns out it's my mistake. I didn't fetch the correct data element in mysql C connector's result set. My C++ compiler/runtime(macOS clang-12) didn't throw any exception when I use the pybind11 built module. And finally, both of these two API works correctly after I fix my bug: 
 Personally, I prefer the second API since it's avoid raw pointer. | 
Beta Was this translation helpful? Give feedback.
                  
                    0 replies
                  
                
            
      Answer selected by
        linrongbin16
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
        
    
Turns out it's my mistake. I didn't fetch the correct data element in mysql C connector's result set.
My C++ compiler/runtime(macOS clang-12) didn't throw any exception when I use the pybind11 built module.
And finally, both of these two API works correctly after I fix my bug:
UserModel *get_user1(const std::string &user_name) const(create new instance and return to pybind11, returnnullptrif no user exists)std::optional<UserModel> get_user2(const std::string &user_name) const(return copy of instance to pybind11, returnstd::nulloptif no user exists)Personally, I prefer the second API since it's avoid raw pointer.