Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support nullable external_ptr<> #312

Open
krlmlr opened this issue Apr 2, 2023 · 1 comment
Open

Support nullable external_ptr<> #312

krlmlr opened this issue Apr 2, 2023 · 1 comment

Comments

@krlmlr
Copy link
Member

krlmlr commented Apr 2, 2023

Currently, a nullptr but not an R_NilValue can be assigned to an external_ptr<> object. This is inconsistent and surprising, in particular because the roundtrip works correctly the other way. Should we support this?

CC @hannes @Tmonster.

library(cpp11)

# Works
cpp_source(
  code = '
  #include "cpp11/external_pointer.hpp"
  #include "cpp11/strings.hpp"

  [[cpp11::register]]
  cpp11::external_pointer<int> test() {
    return cpp11::external_pointer<int>(nullptr);
  }
  '
)

test()
#> NULL

# Fails, but perhaps shouldn't
cpp_source(
  code = '
  #include "cpp11/external_pointer.hpp"
  #include "cpp11/strings.hpp"

  [[cpp11::register]]
  cpp11::external_pointer<int> test() {
    return cpp11::external_pointer<int>(R_NilValue);
  }
  '
)

test()
#> Error: Invalid input type, expected 'externalptr' actual 'NULL'

Created on 2023-04-02 with reprex v2.0.2

@stephematician
Copy link

I can't see a good reason why it shouldn't accept R_NilValue (given that that is what the default constructor assigns). A simple change to external_pointer::valid_type() should fix this, i.e.

  static SEXP valid_type(SEXP data) {
    if (data == nullptr) {
      throw type_error(EXTPTRSXP, NILSXP);
    }
    if (TYPEOF(data) != EXTPTRSXP && data != R_NilValue) {
      throw type_error(EXTPTRSXP, TYPEOF(data));
    }

    return data;
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants